2016-05-30 62 views
0

我有一个基类动物和派生类的狗,猫。C++基类指针,集合类

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

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

+2

请显示一些代码。你的最后一段对我来说有点困惑。我明白这是作业。这听起来像你被要求使用'AnimalCollection'而不是'DogCollection'和'CatCollection',但我无法理解你的最终问题。 – Rotem

+1

我的理解你被要求有一个指向'动物'的指针的容器,你在那里存储指向'狗'和'猫'的指针。所以,我想,你正在谈论虚拟调度。 – lapk

+1

我相信你正在寻找的是 '狗wMyDog;' '动物* wAnimal = wMyDog;' – Ceros

回答

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

+0

嗯,这依赖于事实,你可能需要的实例或一些数组操作进行具体的操作,你会想要封装在不同的类中。 – Ceros

+0

@ coyotte508 doStuff()属于哪个类? – AppleSh

+0

如果它是'虚拟'并在子类“Cat”和“Dog”中重写,那么将调用用于“猫”或“狗”的那个。我将尽快编辑一个实例。 – coyotte508