使用抽象类来实现派生类的元素堆栈

Pat*_*ity 0 c++ virtual stack abstract-class derived-class

我必须在我的大学进行基础C++讲座,所以要明确一点:如果我被允许,我会使用STL.

问题:我有一个名为"shape3d"的类,我从中派生出类"cube"和"sphere".现在我必须实现"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
Run Code Online (Sandbox Code Playgroud)

但是,不幸的是,编译器告诉我:

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
Run Code Online (Sandbox Code Playgroud)

我想这一定是我自己造成的某种非常难看的设计错误.那么如何使用我的堆栈中使用"shape3d"派生的各种对象的正确方法呢?

Geo*_*che 7

您无法从抽象类创建对象.
您可能希望创建一个允许抽象类的指针数组,并使用派生实例填充它们:

// declaration somewhere:
shape3d** array_;

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

// fill later, triangle is derived from shape3d:
array_[0] = new triangle;
Run Code Online (Sandbox Code Playgroud)