![](/img/trans.png)
[英]How do I add child class objects to a vector of their parent class (C++)?
[英]C++ Adding objects of child classes to a vector of a parent class
我有以下 class 层次结构:鳄鱼 Class 从卵生延伸,从动物延伸
我需要将 Crocodile、Goose、Pelican、Bat、Whale 和 SeaLion 类型的对象存储在向量中,因此:
1-我创建全局向量:
vector<Animal*> animals;
2- 我将对象(鳄鱼、鹅、鹈鹕、蝙蝠、鲸鱼、海狮)添加到向量中:
animals.push_back(new Crocodile(name, code, numberofEggs));
3-我循环遍历向量以在桌子上打印每个 object
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
}
我认为它与父子 class 的这篇帖子 std::vector 有关,我认为问题是 object 切片,所以我尝试像这样创建向量:
vector<unique_ptr<Animal>> animals;
//and adding the objects like this
animals.push_back(unique_ptr<Animal>(new Crocodile(name, code, numberofEggs)));
但是什么都没有
任何帮助都会很棒! 谢谢!
您的问题是您尝试从具有父类型的 object 访问未在父 class 中定义的特定子方法。
您应该将 object 存储为要使用的类型,因此,如果您存储Animal
数组,则意味着您将仅使用Animal
接口处理对象,而不管初始 object 类型如何。 否则,如果您需要从Opivarous
class 访问方法,您应该考虑将您的对象存储为Opivarous
(或Crocodile
等)。
此外,您可以为此目的使用dynamic_cast
:
if(Crocodile* crocodile = dynamic_cast<Crocodile*>(animals[i]))
{
cout << crocodile->GetNumberofEggs();
}
这是解决问题的最简单方法,但它表明您的代码中存在架构问题。
我让它在动物 class 上使用虚拟“打印”方法,然后从子类中覆盖此方法。 谢谢大家!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.