空指针访问类成员函数
//空指针访问类成员函数
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 5 class Person 6 { 7 public: 8 void showinfo() 9 { 10 cout << "空指针访问成员函数成功" << endl; 11 } 12 13 void showinfo1() 14 { 15 cout << age << endl; 16 } 17 18 void showinfo2() 19 { 20 cout << this->age << endl; 21 } 22 23 void showinfo3() 24 { 25 if (this==NULL) 26 { 27 return; 28 } 29 cout << this->age << endl; 30 } 31 32 private: 33 int age; 34 }; 35 36 int main() 37 { 38 Person *p = NULL; 39 p->showinfo(); 40 //p->showinfo1();空指针报错 41 //p->showinfo2();空指针报错 42 p->showinfo3();//判断空值习惯,增强代码健壮性,不报错 43 44 system("pause"); 45 return 0; 46 }