基类的C ++数组,具有存储在数组元素中的派生类的实例 [英] C++ array of base class which has instances of derived classes stored in the elements of the array
问题描述
我正在创建一个应用程序,允许用户定义不同形状的尺寸,并使用他们指定的尺寸将面积返回给用户.
I am creating an application that allows a user to define dimensions for different shapes and returns the area to the user using the dimensions they specified.
我的基础课是Shape.派生类为Triangle,Circle,Square和Rectangle.
My base class is Shape. Derived classes are Triangle, Circle, Square and Rectangle.
我创建了一个Shape数组,希望在运行时创建并存储该数组中任何派生类的实例.
I have created an array of Shape in the hope of creating and storing instances of any of the derived classes in the array during runtime.
Shape** shape = new Shape*[TOTAL_SHAPES];
shape[i] = new Circle(radius);
我已经解决了这个问题,但是我无法访问实例化的类方法.抱歉,如果这是一个愚蠢的问题,我对C ++还是陌生的.
I have managed this, however I am unable to access the instantiated classes methods. Sorry if this is a stupid question I am fairly new to C++.
推荐答案
让我们假设您的类型具有以下定义
Let's assume your types had the following definition
class Shape {
public:
void Method1() { ... }
};
class Circle : public Shape {
void Method2() { ... }
}
使用此定义,您可以执行以下操作来访问 Shape
上的方法
With this definition you could access methods on Shape
by doing the following
shape[i]->Method1();
尽管在这种情况下,由于编译器只知道 Shape
,而不是 Circle
,所以无法访问 Method2
./p>
In this context though it wouldn't be possible to access Method2
though because the compiler only knows about Shape
, not Circle
.
shape[i]->Method2(); // Error!
这篇关于基类的C ++数组,具有存储在数组元素中的派生类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!