【发布时间】:2016-04-21 18:18:08
【问题描述】:
假设我们有一个名为 Vehicle 的抽象类:
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 变体的答案也很好?
【问题讨论】:
标签: c++ polymorphism virtual-functions dynamic-dispatch