问题描述
假设我有一个基类Shape,派生类Triangle,Square和Circle。
Shape的成员是一个intshapeType。
Suppose I have a base class "Shape", and derived classes "Triangle", "Square", and "Circle".A member of "Shape" is an int "shapeType".
如果shapeType == 1,那么它是一个三角形。
如果shapeType == 2,那么它是一个正方形。
如果shapeType == 3,那么它是一个圆。
If shapeType==1, then it's a triangle.If shapeType==2, then it's a square.If shapeType==3, then it's a circle.
我有兴趣知道,我只有一个Shape对象,对象,如果有一种方法通过使用shapeType值动态下降到适当的派生类。
I'm interested in knowing given I have just a "Shape" object that was once a derived-object, if there is a way to "dynamically" down-cast to the proper derived class by using the shapeType value.
我知道我可以做一个硬代码switch语句,大致如下:
I know I can do a hard-code switch statement, roughly like:
Triangle* t;
Square* s;
Circle* c;
switch (shape->shapeType) {
case 1:
t = (Triangle*)shape;
case 2:
...
}
上面需要我做一个指针的EVERY派生类的可能性。我想知道是否有一种方法来做这个没有硬编码每个类,而是以某种方式确定类类型映射,其中关键是shapeType和值是类类型。
However, the above requires me to make a pointer of EVERY derived class possibility. I am wondering if there is a way to do this without hard-coding every class, but instead somehow determine the class type map where the key is the shapeType and the value is the class type.
推荐答案
如果他们有虚函数,则使用 dynamic_cast
:
If they've virtual functions, then use dynamic_cast
:
t = dynamic_cast<Triangle*>(shape);
if ( t )
{
//use t
}
但是请注意:你应该尝试以这样一种方式定义类和虚函数,你几乎不需要使用 dynamic_cast
。一般来说,喜欢定义良好的接口和多态性。
But take a note: you should try defining the classes and virtual functions in such a way that you would hardly need to use dynamic_cast
. Prefer well-defined interface, and polymorphism, in general.
以下是一个示例,
class Shape
{
public:
~virtual Shape() {} //destructor must be virtual - important!
virtual double Area() const = 0;
};
class Triangle : public Shape
{
public:
Triangle(double a, double b, double c);
virtual double Area() const
{
//calculate area and return it!
}
};
Shape *s = new Traingle(10,20,30);
double aread = s->Area(); //calls Traingle::Area()
不需要使用 shapeType
变量。
这篇关于C ++向下转换到基于变量的派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!