【发布时间】:2020-08-21 05:55:42
【问题描述】:
我有两个类,基类和派生类。 基类有一个虚方法。
这是我的测试示例:
class Base
{
public:
virtual void Hello() { cout << "-> Hello Base" << endl; }
};
class Derived: public Base
{
public:
void Hello() { cout << "-> Hello Derived" << endl; }
};
int main()
{
Base *mBase = new Base;
// something to do
....
Derived *mDerived = dynamic_cast<Derived*>(mBase);
mDerived->Hello();
return 0;
}
我希望使用mBase 转换为mDerived 之后派生的类的Hello() 方法。
但问题是,当我尝试使用dynamic_cast 时,它会导致应用程序崩溃,如果我使用reinterpret_cast 不是,则将调用Base 类的Hello() 方法。
dynamic_cast案例中的结果:
Segmentation fault (core dumped)
dynamic_cast案例中的结果:
-> Hello Base
【问题讨论】:
-
Base *mBase = new Base;应该是Base *mBase = new Derived; -
您创建了一个
Base对象并尝试将其强制转换为无法工作的Derived -
dynamic_cast<Derived*>(mBase);将返回空指针,因为mBase不指向Base对象的Base子对象,因此您取消引用无效指针。出于同样的原因,使用reinterpret_cast返回的指针也将是未定义的行为 -mBase不指向Derived对象的Base子对象。 -
您是否希望通过强制转换来更改对象的类型?它没有。
标签: c++ polymorphism dynamic-cast reinterpret-cast