指向对象的空指针也可以访问对象成员,因此需要加判断this是否空来保证代码健壮性;
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
int m_age;
void ShowClassName()
{
cout << "this is class Person!" << endl;
}
void ShowPersonName()
{
if (this == NULL)
{
return;
}
cout << "Person's name is" <<m_age<< endl;
}
};
int main()
{
Person* p = NULL;
p->ShowClassName();
p->ShowPersonName();
system("pause");
return 0;
}