c++中空指针也是可以调用成员函数的,但也要注意有没有用到this指针。
如果用到this指针,需要加以判断保证代码的健壮性。
#include <iostream>
using namespace std;
//空指针调用成员函数
class Person {
public:
void showclassname() {
cout << "this is person class" << endl;
}
void showpersonage() {
//不加if的报错原因是因为传入的指针为NULL
if (this == NULL) {
return;
}
cout << "age=" << m_Age << endl;
}
int m_Age;
};
void test01() {
Person* p = NULL;
p->showclassname();
p->showpersonage();
}
void test02() {
}
int main() {
test01();
test02();
system("pause");
return 0;
}