【问题标题】:Iterate over different objects迭代不同的对象
【发布时间】:2017-09-30 08:38:45
【问题描述】:

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

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
}

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

【问题讨论】:

  • 装“所有水果”的容器是什么?因为你不能迭代一些像“所有水果”这样模糊的概念,你可以迭代一个容器。
  • 要迭代,你需要一个容器。你没有提到这是一个数组、向量、链表等。
  • 您将水果存放在什么容器中/它是如何声明的?如果它类似于std::vector<std::unique_ptr<fruit>> fruits;,那你为什么不能简单地做for (const auto& a_fruit : fruits) ...
  • StoryTeller 是对的,你需要一个容器。您不能只迭代“所有水果”。

标签: c++ class loops inheritance superclass


【解决方案1】:

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

由于您存储的对象属于不同类型,但具有共同的基本类型,you need to use pointers or references 以实现多态行为并避免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 他们,这是一种非常容易出错的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 2014-04-26
    • 2018-06-10
    相关资源
    最近更新 更多