1

我有一个Mammal家长班。 Dog, Cat,Lion是子类。

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

vector<Mammal> v;

并使用这条线将新对象附加到向量中。

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

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

4

2 回答 2

6

buchipper 已经给了你很好的建议。当您想正确管理宠物的生命周期时,请考虑使用std::unique_ptr<>orstd::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))
于 2015-11-06T07:32:53.310 回答
1

正如评论中已经提到的,你有一个 Mammal 对象的向量,而不是指针或引用。

尝试 -

vector <Mammal *> v;
v.push_back(new Dog(Name, Blue, Owner));
于 2015-11-06T07:23:00.890 回答