【发布时间】:2012-07-05 19:21:14
【问题描述】:
我不确定我是否像我喜欢的那样表达了我的问题,但我会举一个例子来澄清问题。
代码如下:
class Shape;
class Circle;
class Triangle;
class Shape
{
Shape(void);
~Shape(void);
virtual void DrawShape(void) = 0;
}
class Circle : public Shape
{
/* .... constructor/destructor defined normally .... */
bool TestIntersection(Triangle* _triangle);
bool TestIntersection(Circle* _circle);
void DrawShape(void);
}
/* main.cpp */
...
Shape* shape;
Shape* circle = new Circle;
if(a == 0)
{
shape = new Circle;
}
else
{
shape = new Triangle;
}
circle->TestIntersection(shape);
我得到的错误是没有可接受的从 Shape* 到 Circle* 或 Triangle* 的转换。
为什么会这样?还是我需要一种方法来确定已将哪个派生类设置为抽象类指针?
【问题讨论】:
-
Circle不是从Shape派生的。circle.也不起作用,因为circle是一个指针。请您发布一些真实的代码,以免造成混乱? -
(因为试图知道派生类型是什么,是向下转换的第一步)
标签: c++ class abstract-class derived-class