遍历不同的对象

Iterate over different objects

我想遍历所有继承自同一个超对象的不同对象class。这意味着我有一个像这样的超级class:

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

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

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
}

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

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

由于您存储的对象类型不同但具有共同的基类型,you need to use pointers or references to achieve polymorphic behavior and avoid object slicing

例如,您可以使用 std::unique_ptr 个对象的向量。

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 个对象的向量)的优点是当向量被删除时,你的苹果和香蕉对象会自动销毁。否则,您必须手动 delete 它们,这是一种非常容易出错的方法。