假设我们有一个叫做Vehicle
抽象类:虚拟方法覆盖在C++
class Vehicle {
virtual bool raceWith(Vehicle *anotherVehicle) = 0;
};
而且我们有它的子类Bicycle
和Car
:
// forward declaration
class Car;
class Bicycle : public Vehicle {
virtual bool raceWith(Vehicle *anotherVehicle) {
throw SomeExceptionClass();
}
virtual bool raceWith(Car *anotherVehicle) {
return true;
}
virtual bool raceWith(Bicycle *anotherVehicle) {
return false;
}
};
然而,这个代码块抛出SomeExceptionClass:
Vehicle *aBicycle = new Bicycle();
Vehicle *aCar = new Car();
aBicycle->raceWith(aCar);
他该怎么做回覆? C++不允许我们以这种方式使用多态方法吗?
任何帮助将不胜感激。谢谢。
编辑:这也将很好提供与dynamic_cast<>
和decltype
变种的答案?
什么是双派遣? – Leviathlon
@Leviathlon双虚拟调度是根据** two **对象的动态类型调用正确实现的能力。 C++仅在'this'上提供单个虚拟调度。这里所描述的flatmouse被称为访问者模式,并且使用单次调度两次来实现双重调度。 – Quentin
这解决了这个问题。这样一个很好的答案。感谢您的关注。 – Leviathlon