C++ 将子类的对象添加到父类的向量中
C++ Adding objects of child classes to a vector of a parent class
我有以下类层次结构: 鳄鱼类从卵生延伸,从动物
延伸 我需要将鳄鱼、鹅、鹈鹕、蝙蝠、鲸鱼和海狮类型的对象存储在矢量中,因此:
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 类上使用虚拟的"打印"方法,然后从子类中覆盖此方法。谢谢大家!
相关文章:
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- C++读取行到类向量
- 在运行时选择父类的实现
- 如何在C++子类中访问父类的私有变量
- 将父类的子类的数据复制到具有相同父类的另一个类
- 父类的私有函数会导致对具有相同名称和相似参数的子类中的公共函数的不明确调用
- C++ 将子类的对象添加到父类的向量中
- 两个父类的构造函数的序列
- 为什么我的子类不继承父类的字符串?
- C++调用使用重写函数的父类函数
- 在父类中公开受保护的构造函数
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 如何使父类不重复已经执行的祖父方法
- 从父类的向量访问子类函数,而无需向下转换
- 比较从父类继承但存储在父类的向量中的类的对象类型
- 在C++中将派生类类型的向量链接到父类类型的向量
- 在父类的向量上调用子类的方法