使用抽象类实现派生类的元素堆栈 我必须在我的大学里做一个基础的C++讲座,所以我要清楚:如果我允许的话,我会使用STL。
问题是:我有一个名为shape3d的类,我从中派生了类cube和sphere。现在我必须实现shape3d_堆栈,这意味着能够容纳立方体和球体类型的对象。我为此使用了数组,当我尝试使用一堆int时,它运行得非常好。我试着这样做: shape3d_stack.cpp:使用抽象类实现派生类的元素堆栈 我必须在我的大学里做一个基础的C++讲座,所以我要清楚:如果我允许的话,我会使用STL。,c++,stack,virtual,abstract-class,derived-class,C++,Stack,Virtual,Abstract Class,Derived Class,问题是:我有一个名为shape3d的类,我从中派生了类cube和sphere。现在我必须实现shape3d_堆栈,这意味着能够容纳立方体和球体类型的对象。我为此使用了数组,当我尝试使用一堆int时,它运行得非常好。我试着这样做: shape3d_stack.cpp: 15 // more stuff 16 17 shape3d_stack::shape3d_stack (unsigned size) : 18 array_ (NULL), 19
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;
线路
array_ = new shape3d[size];
分配shape3d对象的数组。不是立方体,不是球体,只是普通的旧形状3d。但是,即使创建一个shape3d对象也是不可能的,因为它是抽象的
一般来说,要使用多态性和虚拟函数,您需要使用间接寻址:指针和/或引用,而不是文字对象。shape3d*可能指向立方体或球体,但shape3d始终是shape3d,而不是shape3d的子类。由于shape3d是抽象基类,您可能希望堆栈存储指向shape3d的指针,而不是实际对象。您无法创建抽象类的新数组。您可以将其声明为指针数组,然后在知道它是哪种类型的形状后,可以分配所选派生类的对象。您需要创建指向对象的指针堆栈,而不是对象堆栈