C++基类指针、集合类

标签 c++ inheritance polymorphism

我有一个基类 Animal 和派生类 Dog、Cat。

我还有一个 DogCollection、CatCollection 类来管理诸如添加新猫等操作、读取猫、从数据库中删除猫、使用指向 Dog 和 Cat 类的指针搜索特定猫。

有人要求我使用基类指针来管理单个容器中的类。为此,在 Dog 和 Cat 类中执行读取和写入操作而不是单独的 DogCollection 和 CatCollection 类是否更好?

最佳答案

在常见的 c++ 中,您通常会使用模板化容器来保存对象,如下所示:

#include <vector>

class Cat;
class Dog;
class Animal;

typedef std::vector<Cat*> CatCollection;
typedef std::vector<Dog*> DogCollection;
typedef std::vector<Animal*> AnimalCollection;

我用了std::vector作为容器,但还有其他可用的。

然后您可以将容器作为容器来操作,并对项目本身执行操作,例如:

AnimalCollection coll;

//add elements
Cat *cat = ...;
Dog *dog = ...;

coll.push_back(cat);
coll.push_back(dog);

//do something with the first item of the collection
coll[0] -> doStuff();

//do something on all items
for (Animal *c: coll) {
    c -> doStuff();
}

//Don't forget to delete allocated objects one way or the other
//std::vector<std::unique_ptr<Animal>> can for example take ownership of pointers and delete them when the collection is destroyed

可以在特殊情况下为特定类型创建特定集合类,但这并不常见。

Live Demo

关于C++基类指针、集合类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37530924/

相关文章:

javascript - 基于原型(prototype)继承在实际项目中的应用

haskell - 哪些类型的问题可以帮助 "higher-kinded polymorphism"更好地解决?

c++ - Const 重载和多态性

c# - 您如何处理具有不同类型结果的重写函数?

c++ - 有人可以推荐一本关于可移植 C/C++ 代码开发的书吗?

c++ - 是什么导致我的循环在其第一次迭代中运行得更慢?

c++ - 如何在不完全 boost 的情况下使用 boost.xpressive ?

C++ 继承 : function signatures for base type not working with derived type

javascript - 作为自身父对象的 javascript 对象?

c++ - 在 C++ 中使用构造函数编译问题