使用 NULL 类指针,可以调用类成员函数.这怎么可能

Using NULL class pointers, class member functions can be called. How is this possible?

本文关键字:成员 函数 调用 怎么可能 NULL 指针 使用      更新时间:2023-10-16
#include <iostream>
using namespace std;
class A
{
public :
    void show()
    {
        cout << "A "  << endl;
    }
};
class B : public A
{
public :
    void show()
    {
        cout << "B "  << endl;
    }
};
int main()
{
    A *a =NULL;
    a->show(); // Prints 'A'
    B *b =NULL;
    b->show(); // Prints 'B'
}

这是如何打印的,当我们从A继承showB时,如何使用B类对象调用show()?从B继承A时究竟会发生什么?

这是未定义的行为,但许多实现的行为方式与您所看到的方式相同。 考虑以下调用:

a->show();

编译器可以看到 A 没有基类,并且show()不是虚拟的。 因此,唯一可能调用的函数是 A::show() 。 太好了,调用它! 您需要做的就是(如果您是编译器(将a传递为this,即函数的隐藏第一个参数。 如果函数中从未使用this,它很可能工作正常。

即便如此,这也不能保证有效,不可移植,并且是一个坏主意。 别这样。 你的裤子可能会烫伤。