C ++基类指针,集合类

时间:2016-05-30 17:23:07

标签: c++ inheritance polymorphism

我有一个基类动物和派生类Dog,Cat。

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

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

1 个答案:

答案 0 :(得分:2)

在常见的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