c++ - 为什么动态转换的指针执行为 NULL 的派生类对象?
问题描述
我编写了一个代码,它使用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;博士; 是“未定义的行为”
一旦您的代码取消引用空指针,所有赌注都将关闭。在这种情况下,编译器假设空指针指向它的静态类型的有效对象,并直接调用它的 [edit: non] 虚拟方法的实现。
推荐阅读
- elasticsearch - apache flink、elasticsearch和kafka集成的版本
- laravel - 无法在 Google Compute Engine 上部署容器映像
- botframework - MS Teams 机器人在用户的时区显示时间
- python - 在 django 视图中过滤显示的对象
- android - RecyclerView 行的数据在滚动时变得混乱
- python - 如何让一个 python 文件要求用户输入,然后将此输入传递给第二个 .py 文件?
- html - 如何为聊天气泡创建循环?
- javascript - 谷歌折线图中从左到右的启动动画
- android - 通过标签获取最后一个片段
- file - 在 Jenkins 中获取上传的文件