首页 > 解决方案 > 为什么动态转换的指针执行为 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()方法的输出?

标签: c++pointersinheritancedynamic-cast

解决方案


tl;博士; 是“未定义的行为”

一旦您的代码取消引用空指针,所有赌注都将关闭。在这种情况下,编译器假设空指针指向它的静态类型的有效对象,并直接调用它的 [edit: non] 虚拟方法的实现。


推荐阅读