【发布时间】:2012-12-09 23:11:16
【问题描述】:
这里用代码解释:
//Sphere and Box inherit from IShape
//
//Sphere methods:
//bool Sphere::Intersect(Sphere* sphere)
//bool Sphere::Intersect(Box* box);
//
//Box methods:
//bool Box::Intersect(Sphere* sphere)
//bool Box::Intersect(Box* box)
IShape* shapeA;
IShape* shapeB;
shapeA= new Sphere();
shapeB= new Box();
bool areTheyIntersecting = shapeA->Intersect(shapeB); //problem is here?
这种使用多态性的方法会起作用吗,还是我必须寻找另一种方法让类识别彼此的类型,以便它们知道要调用的正确方法?
【问题讨论】:
-
这里需要双重调度...
-
为什么不直接使用静态类型呢? IShape 是一个非常糟糕的主意。
-
所以我可以稍后将它们(IShape 变量)放在 1 个数组中,以便更轻松地制作 CompositeShape
标签: c++ inheritance polymorphism abstract-class