2009-10-19 152 views
0

我要爲我的大學基本的C++講座做到這一點的元件的堆疊,所以僅僅是明確的:我已經使用了STL,如果我被允許。使用抽象類來實現派生

的問題:我有一個名爲「一個Shape3D」我從中派生的類「魔方」和「球」類。現在我必須實現「shape3d_stack」,這意味着可以保存「cube」和「sphere」類型的對象。我爲此使用了數組,當我嘗試使用一堆int時,它工作得很好。我試圖做到這一點,像這樣:

shape3d_stack.cpp:

15 // more stuff 
16  
17  shape3d_stack::shape3d_stack (unsigned size) : 
18   array_ (NULL), 
19   count_ (0), 
20   size_ (size) 
21  { array_ = new shape3d[size]; } 
22  
23 // more stuff 

但不幸的是,編譯器告訴我:

g++ -Wall -O2 -pedantic -I../../UnitTest++/src/ -c shape3d_stack.cpp -o shape3d_stack.o 
shape3d_stack.cpp: In constructor ‘shape3d_stack::shape3d_stack(unsigned int)’: 
shape3d_stack.cpp:21: error: cannot allocate an object of abstract type ‘shape3d’ 
shape3d.hpp:10: note: because the following virtual functions are pure within ‘shape3d’: 
shape3d.hpp:16: note: virtual double shape3d::area() const 
shape3d.hpp:17: note: virtual double shape3d::volume() const 

我想這一定是某種真難看的設計我自己造成的錯誤。那麼在我的棧中使用從「shape3d」派生的各種對象的正確方式是什麼?

回答

7

不能創建抽象類的對象。
你可能想創建一個指針數組抽象類,這是允許的,並與衍生的實例填補他們:

// declaration somewhere: 
shape3d** array_; 

// initalization later: 
array_ = new shape3d*[size]; 

// fill later, triangle is derived from shape3d: 
array_[0] = new triangle; 
3

array_ = new shape3d[size]; 

分配了Shape3D數組對象。不是立方體,不是球體,只是普通的舊shape3d。但是,即使創建一個shape3d對象也是不可能的,因爲它是抽象的。

一般情況下,使用多態和虛函數,你需要使用間接:指針和/或引用,而不是字面的對象。 shape3d *可能指向一個立方體或球體,但shape3d始終是shape3d,而不是shape3d的子類。

0

由於shape3d是一個抽象基類,您可能希望您的堆棧存儲指向shape3d的指針,而不是實際的對象。

0

不能創建抽象類的一個新的數組。你可以做的是將它聲明爲一個指針數組,然後當你知道它是哪種類型的形狀時,你可以分配你選擇的派生類的對象。

0

相反物品堆的,你需要創建到對象的堆棧指針的。

相關問題