gpt4 book ai didi

C++基类指针、集合类

转载 作者:行者123 更新时间:2023-11-28 02:05:57 25 4
gpt4 key购买 nike

我有一个基类 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/

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