好吧,我认为这段代码和程序输出可以自我解释:
#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)
程序输出:
没有对象调用的非静态函数?
为什么会这样?
未定义的行为.您的程序通过在空指针上调用方法来调用未定义的行为,因此允许所有内容,包括输出.
请记住:C++语言的规范没有指定每个可能程序的输出,以便为优化留出空间.许多事情没有明确检查,可能导致行为似乎不正确或不合逻辑,但根本没有说明.