繁体   English   中英

父类对象的动态数组以保存子对象

[英]Dynamic array of objects of parent class to hold child objects

我有一个Mammal父类。 DogCatLion是子类。

我正在使用向量将所有子类保存为Mammal对象

vector<Mammal> v;

并使用此行将新对象附加到向量。

v.push_back(new Dog(Name, Blue, Owner));

显然它不起作用。 Error no instance of overload function在编译期间Error no instance of overload function抛出给我。 我是C ++的新手,所以我不确定动态创建父类数组以容纳所有子对象的正确方法是什么

buchipper已经为您提供了很好的建议。 当您要正确管理宠物的寿命时,请考虑使用std::unique_ptr<>std::shared_ptr<>代替原始指针:

// the vector owns the pets and kills them, when they are removed
// from the vector
vector<std::unique_ptr<Mamal> > v1

// the vector has shared ownership of the pets. It only kills them,
// when noone else needs them any more
vector<std::shared_ptr<Mamal> > v2

// the vector has no ownership of the pets. It never kills them.
vector<Mamal*> v3

在最后一种情况下,其他人必须照顾宠物的死亡,否则它们会像僵尸一样在您的记忆中徘徊。 您不想那样对待宠物,对吗?

更新哦,我忘了提,你应该更喜欢make_shared()make_unique()在新的,或使用emplace_back()代替push_back()

v1.emplace_back(new Dog{Name, Blue, Owner});
v1.push_back(make_unique<Dog>(Name, Blue, Owner))

v2.emplace_back(new Dog{Name, Blue, Owner});
v2.push_back(make_shared<Dog>(Name, Blue, Owner))

正如评论中已经提到的,您拥有哺乳动物对象的向量,而不是指针或引用。

尝试-

vector <Mammal *> v;
v.push_back(new Dog(Name, Blue, Owner));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM