我必须在我的大学做一个基本的 C++ 讲座,所以要明确一点:如果允许的话,我会使用 STL。
问题:我有一个名为“shape3d”的类,从中派生了“cube”和“sphere”类。现在我必须实现“shape3d_stack”,这意味着能够保存“立方体”和“球体”类型的对象。我为此使用了数组,当我尝试使用一堆整数时它工作得很好。我试着这样做:
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”派生的各种对象的正确方法是什么?