我不確定我是否像我喜歡的那樣描述了我的問題,但我會舉例說明清楚。確定哪個派生類指向抽象類的指針設置爲
下面是代碼:
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);
我得到的,有從外形*金環*或*三角沒有可接受的轉換中的誤差。
這是怎麼發生的?或者我需要一種方法來確定哪個派生類已被設置爲抽象類指針?
'Circle'不是從'Shape'派生的。另外'circle.'不會工作,因爲'circle'是一個指針。請你可以發佈一些真實的代碼,以避免混淆? – 2012-07-05 11:33:59
[訪問者模式如何避免向下轉換](http://stackoverflow.com/questions/3254788/how-visitor-pattern-avoid-downcasting) – 2012-07-05 11:40:16
(因爲試圖知道派生類型是什麼,是第一步在downcasting) – 2012-07-05 11:40:52