c++ - 使用抽象类实现派生类的元素栈

标签 c++ stack virtual abstract-class derived-class

我必须在我大学的基础 C++ 讲座中这样做,所以明确一点:如果允许的话,我会使用 STL。

问题:我有一个名为“shape3d”的类,我从中派生了“立方体”和“球体”类。现在我必须实现“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”派生的各种对象的正确方法是什么?

最佳答案

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

// declaration somewhere:
shape3d** array_;

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

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

关于c++ - 使用抽象类实现派生类的元素栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1591269/

相关文章:

C++ 添加对象到数组

linux - 虚拟linux系统

c++ - 是否可以从 std::set 中删除修改后的元素?

c++ - Qt控制台: Log all stdin and stdout to file

linux - Linux 上的 JNI_CreateJavaVM 会破坏堆栈?

Java-静态变量,但扩展子类不共享该值

c++11 - C++0x 中的最终虚函数

c++ - QPainterPath 文本在打印时呈现错误

c++ - 从 C++ 静态库导出变量

node.js - React-navigation-camera 与 React-navigation-stack 冲突并且