0

我必须在我的大学做一个基本的 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”派生的各种对象的正确方法是什么?

4

5 回答 5

7

您不能从抽象类创建对象。
您可能希望创建一个指向抽象类的指针数组,这是允许的,并用派生实例填充它们:

// declaration somewhere:
shape3d** array_;

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

// fill later, triangle is derived from shape3d:
array_[0] = new triangle;
于 2009-10-19T21:31:02.450 回答
3

线

array_ = new shape3d[size];

分配一个 shape3d 对象数组。不是立方体,不是球体,只是普通的旧 shape3d。但它甚至不可能创建一个 shape3d 对象,因为它是抽象的。

通常,要使用多态性和虚函数,您需要使用间接:指针和/或引用,而不是文字对象。shape3d* 可能指向立方体或球体,但 shape3d 始终是 shape3d,而不是 shape3d 的子类。

于 2009-10-19T21:32:00.257 回答
0

由于shape3d是一个抽象基类,您可能希望堆栈存储指向 的指针shape3d,而不是实际对象。

于 2009-10-19T21:32:07.673 回答
0

您不能创建抽象类的新数组。您可以做的是将它声明为一个指针数组,然后当您知道它是哪种类型的形状时,您可以分配您选择的派生类的对象。

于 2009-10-19T21:34:40.117 回答
0

您需要创建一个指向对象的指针堆栈,而不是一堆对象。

于 2009-10-19T21:35:05.820 回答