2016-05-30 52 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