gpt4 book ai didi

c++ - 父类对象的动态数组,用于保存子对象

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:06 27 4
gpt4 key购买 nike

我有一个 Mammal 父类。Dog, Cat, Lion 是子类。

我正在使用 vector 将所有子类保存为 Mammal 对象本身

vector<Mammal> v;

并使用这一行将新对象附加到 vector 。

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

显然它不起作用。 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))

关于c++ - 父类对象的动态数组,用于保存子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33561304/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com