【发布时间】: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