用于容纳子对象的父类对象的动态数组
Dynamic array of objects of parent class to hold child objects
我有一个Mammal
父类。Dog
、Cat
、Lion
是子类。
我使用向量将所有子类作为Mammal
对象保存为
vector<Mammal> v;
并使用这条线将新对象附加到向量中。
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))
正如评论中已经提到的,您有一个Mammal对象的向量,而不是指针或引用。
尝试-
vector <Mammal *> v;
v.push_back(new Dog(Name, Blue, Owner));
相关文章:
- C++中的动态对象与非动态对象
- 对具有动态分配的内存和析构函数的类对象的引用
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 生成文件:动态源文件名和对象目录
- 我们可以通过 IPC 传递具有动态管理成员的类对象吗?
- 使用动态实例化的对象填充矢量的快速方法
- 如何在 Cheerp/js 中迭代动态命名的对象?
- 销毁C++中动态分配的内存(数组对象)
- 创建动态对象并将其推送到矢量中
- 删除包含包含动态对象的 STL 容器的智能指针
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 将基类分配给派生对象,反之亦然,以C++以及静态和动态对象之间的差异
- 如何访问对象动态数组中的私有成员变量?
- 如果您为类的一个对象动态分配内存作为参数,会发生什么
- Cython 中对象动态大小的数组
- malloc分配的对象动态类型是什么
- C++按属性排序的对象动态数组
- visual C++新与Malloc的对象动态内存阵列