C++中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针。
//空指针访问成员函数
class Person {
public:
void ShowClassName() {
cout << "我是Person类!" << endl;
}
void ShowPerson() {
if (this == NULL) {
return;
}
cout << mAge << endl;
}
public:
int mAge;
};
void test01()
{
Person * p = NULL;
p->ShowClassName(); //空指针,可以调用成员函数
p->ShowPerson(); //但是如果成员函数中用到了this指针,就不可以了
}
int main() {
test01();
system("pause");
return 0;
}
空指针可以调用成员函数,但是如果用到了默认的this指针(属性的前面,默认有一个this->),就不可以了。
空指针还访问里面的成员,本身自相矛盾,所以会报错。
所以为了防止这种空指针的情况,增强代码的健壮性:需要在调用之前,检查是否为NULL。所以就有了if条件这种情况。