为什么动态转换的指针执行为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;dr;是“未定义的行为”

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...