为什么可以在没有对象实例的情况下调用非静态成员函数?

cod*_*ddy 6 c++

可能重复:
当我在NULL对象指针上调用成员函数时会发生什么?

好吧,我认为这段代码和程序输出可以自我解释:

#include <iostream>
#include <string>
using namespace std;

class Test
{
public:
    void Not_Static(string args)
    {
        cout << args << endl;
    }
};

int main()
{
    Test* Not_An_instance = nullptr;
    Not_An_instance->Not_Static("Non-static function called with no object?");
    cin.ignore();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

程序输出:

没有对象调用的非静态函数?

为什么会这样?

thi*_*ton 9

未定义的行为.您的程序通过在空指针上调用方法来调用未定义的行为,因此允许所有内容,包括输出.

请记住:C++语言的规范没有指定每个可能程序的输出,以便为优化留出空间.许多事情没有明确检查,可能导致行为似乎不正确或不合逻辑,但根本没有说明.


Jon*_*onH 5

此行为未定义 - 因此很可能会打印该输出.问题是未定义的行为可以轻易咬你,所以你不应该做这样的事情.