C++Note 空指针访问成员函数
1 #include <iostream> 2 using namespace std; 3 4 class Person 5 { 6 public: 7 void showClassName() 8 { 9 cout << "This is Person Class" << endl; 10 } 11 void showPersonAge() 12 { 13 cout << "Person Age = " << m_Age << endl;//m_Age默认为 this->m_Age 此时this为空 报错 14 } 15 int m_Age; 16 17 }; 18 void test() 19 { 20 Person* p = NULL; 21 p->showClassName();//正常调用 22 //p->showPersonAge();//报错: 原因是传入的指针为空 23 } 24 int main() 25 { 26 test(); 27 system("pause"); 28 return 0; 29 }
修改showPersonAge() 增加代码的健壮性
1 void showPersonAge() 2 { 3 if (this == NULL) 4 { 5 return; 6 } 7 cout << "Person Age = " << m_Age << endl; 8 }
浙公网安备 33010602011771号