C++ 将子类的对象添加到父类的向量中

C++ Adding objects of child classes to a vector of a parent class

本文关键字:父类 向量 对象 子类 C++ 添加      更新时间:2023-10-16

我有以下类层次结构: 鳄鱼类从卵生延伸,从动物

延伸 我需要将鳄鱼、鹅、鹈鹕、蝙蝠、鲸鱼和海狮类型的对象存储在矢量中,因此:

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 有关,我认为问题是对象切片,所以我尝试像这样创建向量:

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

但什么都没有

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

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

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

此外,您还可以将dynamic_cast用于此目的:

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

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

我让它在 Animal 类上使用虚拟的"打印"方法,然后从子类中覆盖此方法。谢谢大家!