【问题标题】:C++ Adding objects of child classes to a vector of a parent classC++ 将子类的对象添加到父类的向量中
【发布时间】:2020-10-15 10:27:59
【问题描述】:

我有以下类层次结构: Crocodile Class extends from Oviparous which extends from Animal

我需要将 Crocodile、Goose、Pelican、Bat、Whale 和 SeaLion 类型的对象存储在向量中,所以:

1- 我创建了全局向量:

vector<Animal*> animals;

2- 我将对象(鳄鱼、鹅、鹈鹕、蝙蝠、鲸鱼、海狮)添加到向量中:

animals.push_back(new Crocodile(name, code, numberofEggs));

3- 我循环遍历向量以在桌子上打印每个对象

for (size_t i = 0; i < animals.size(); ++i){
    /* now the problem is here, each animal[i] is of type = "Animal", not Crocodile, or Goose, etc..
   /* so when I try to do something like the line below it doesn't work because it can't find the method because that method is not on the Animal Class of course */
   cout << animals[i]->GetName(); // THIS WORK
   cout << animals[i]->GetNumberofEggs(); //THIS DOESN'T WORK
   /* when I debug using the line below, every object on the vector is returning "P6Animal" */
   cout << typeid(animals[i]).name(); // P6Animal instead of Crocodile
}

我认为它与这篇文章std::vector for parent and child class 相关,我认为问题在于对象切片,所以我尝试像这样创建向量:

vector<unique_ptr<Animal>> animals;
//and adding the objects like this
animals.push_back(unique_ptr<Animal>(new Crocodile(name, code, numberofEggs)));

但什么都没有????

任何帮助都会很棒!谢谢!

【问题讨论】:

  • 因为您使用的是指针,所以它不是切片问题。不过,使用智能指针比原始指针更好,所以继续使用它。我怀疑正在发生的事情是您的基类中没有 GetNumberofEggs() 函数。请在minimal reproducible example 上工作。
  • typeid::name 没有您希望的那么有用。该类型实际上是指向Animal 的指针。考虑为动物添加一个name 虚函数。
  • 这里有一个小例子可以帮助解释typeid问题:ideone.com/UWwdXF
  • 我和忍者在一起。但是你愿意为那些鸡蛋走多远?动物有蛋,但很多动物不下蛋,所以根据你所说的GetNumberofEggs,在Animal 中可能没有意义。

标签: c++ arrays inheritance vector object-slicing


【解决方案1】:

我让它在 Animal 类上有一个虚拟的“Print”方法,然后从子类中覆盖这个方法。谢谢大家!

【讨论】:

    【解决方案2】:

    您的问题是您尝试从具有父类型的对象访问未在父类中定义的特定子方法。

    您应该将对象存储为您想要使用的类型,因此如果您存储Animal 的数组,则意味着您将只使用Animal 接口来处理对象,无论初始对象类型。否则,如果您需要访问 Opivarous 类中的方法,您应该考虑将您的对象存储为 Opivarous(或 Crocodile 等)。

    此外,您可以为此目的使用dynamic_cast

    if(Crocodile* crocodile = dynamic_cast<Crocodile*>(animals[i]))
    {
        cout << crocodile->GetNumberofEggs();
    }
    

    这是解决问题的最简单方法,但它表明您的代码中存在架构问题。

    【讨论】:

      猜你喜欢
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-24
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      相关资源
      最近更新 更多