问题描述
我编写了一个代码,它使用 dynamic_cast
运算符来转换指向派生类对象的基类指针。但我对铸造过程有疑问。首先看看源代码和输出。
#include <iostream>
using namespace std;
class Base
{
public:
virtual void BasePrint(void)
{
cout << "This is base print\n";
}
};
class Derived1 : public Base
{
public:
void Derived1print(void)
{
cout << "This is derived1 print\n";
}
};
class Derived2 : public Base
{
public:
void Derived2print(void)
{
cout << "This is derived2 print\n";
}
};
int main(void)
{
Base *ptr = new Derived1;
Derived1 *caster1 = dynamic_cast<Derived1 *>(ptr);
if (caster1 != NULL)
caster1->Derived1print();
Derived2 *caster2 = dynamic_cast<Derived2 *>(ptr);
if (caster2 == NULL) // Doubt in this line
caster2->Derived2print();
return 0;
}
This is derived1 print
This is derived2 print
在第 40 行中写到 if (caster2 == NULL)
然后只运行这一行 caster2->Derived2print();
并且输出在终端中可见!
现在,如果 caster2
指针是 NULL
,那么如何使用箭头运算符 ->
取消引用它以显示 Derived2print()
方法的输出?
解决方法
tl;dr;是“未定义的行为”
一旦您的代码取消对空指针的引用,所有赌注都将结束。在这种情况下,编译器假设空指针指向它的静态类型的有效对象,并直接调用它的 [edit: non] 虚拟方法的实现。