NULL指针能够访问类成员函数 [英] NULL pointer able to access class member function
问题描述
可能重复:
在NULL指针上访问类成员
一个非常愚蠢的问题,也可能是我的概念上的疑问。
A very silly question or may be my conceptual doubt.
#include <iostream>
using namespace std;
class A
{
public:
void print()
{
cout<<"Printing\n";
}
};
int main()
{
A * a = NULL;
a->print();
return 0;
}
输出结果是:Printing
The output is: Printing
如何 a
指针(它为NULL)能够访问类A的成员函数。
How is a
pointer(which is NULL) able to access member function of class A.
请解释...可能是它只是一个愚蠢的问题,但我有一个NULL指针不会访问类的成员函数。
Please explain... may be its just a silly question but I had the impression that a NULL pointer will not access the class's member function.
推荐答案
解释一个 NULL
指针,就像在代码中一样,是未定义的行为。这种
Dereferencing a NULL
pointer, as you do in your code, is undefined behavior. One of the possibilities of such undefinedness is that it may just work. But it may crash the next time, or do something totally unexpected.
因为你没有使用隐式的这个
您的成员函数 print
中的参数似乎像 NULL
指针不需要 dereferenced。
Since you are not using the implicit this
argument in your member function print
, seems like such NULL
pointer never needs to actually be dereferenced.
这篇关于NULL指针能够访问类成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!