我有一个基类 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
可以在特殊情况下为特定类型创建特定集合类,但这并不常见。
关于C++基类指针、集合类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37530924/