gpt4 book ai didi

c++ - 遍历不同的对象

转载 作者:行者123 更新时间:2023-11-30 05:13:50 24 4
gpt4 key购买 nike

我想遍历所有继承自同一个父类(super class)的不同对象。这意味着我有一个像这样的父类(super class):

class fruit
{
public:
fruit()
{
}
};

我有这样的子类,它们定义了我的代码中使用的对象:

class apple: public fruit
{
public:
apple()
{
}
};

class banana: public fruit
{
public:
banana()
{
}
};

现在我想遍历所有水果(苹果、香蕉):

for ( first fuit; last fruit; next fruit )
{
// do something, no matter if apple or banana
}

但是我应该怎么做,因为苹果和香蕉是不同的类类型,但它们共享相同的父类(super class)。这就是为什么我认为,必须有一种优雅的方式来做到这一点。

最佳答案

C++ 没有任何类型的内置对象注册表,您可以在其中访问特定类型的每个现有对象。但是,C++ 有多个 container可用于在各种不同的数据结构中存储多个对象的类型。

由于您存储的对象属于不同类型但具有共同的基类型,you need to use pointers or references实现多态行为并避免object slicing .

例如,您可以使用 std::unique_ptr 的 vector 对象。

std::vector<std::unique_ptr<fruit>> fruits;

fruits.emplace_back(new apple);
fruits.emplace_back(new banana);

for (auto &fruit : fruits) {
// fruit is a reference to the unique_ptr holding the pointer-to-fruit. Use
// the "indirect access to member" operator -> to access members of the
// pointed-to object:

fruit->some_method();
}

使用这种方法(unique_ptr 对象的 vector )的优点是当 vector 是时,你的苹果和香蕉对象会自动销毁。否则,您必须手动删除它们,这是一种非常容易出错的方法。

关于c++ - 遍历不同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43744376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com