空指针访问成员函数(3)

C++空指针是可以调用成员函数的,但是也要注意有没有用到this指针。

如果用到this指针,需要加以判断来保证代码的健壮性。

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Person
 5 {
 6 public:
 7 
 8     void showPersonName(void)
 9     {
10         cout << "This is Person class!" << endl;
11     }
12 
13     void showPersonAge(int age)
14     {
15         //解决办法:增加一个判断来保证代码的健壮性
16         if (this == NULL)
17         {
18             return;
19         }
20 
21         this->m_Age = age;
22         cout << this->m_Age << endl;//所以this指针就是一个空指针!并没有确切的指向一个存在的数据,所以无法访问
23     }
24 
25     int m_Age;
26 };
27 
28 void test_01(void)
29 {
30     Person *p = NULL;//因为这里Person的指针指向的是一个空对象!
31 
32     //p->showPersonName();//空指针可以调用成员函数
33 
34     //但是这里就不可以了,系统会报错p是空指针,原因是什么呢?
35     p->showPersonAge(10);//因为类属性的前面都默认增加了一个this指针,表示这是当前对象的一个属性,但是这里的指针p指向的是一个空对象
36 }
37 
38 int main(void)
39 {
40     test_01();
41 
42     system("pause");
43     return 0;
44 }

Person指针p为空,表明p指向一个空对象,间接导致了调用成员函数时,this指针也为空(NULL),所以增加一个判断this指针的条件函数,当this指针为空时,直接跳出成员函数即可 。

posted @ 2020-04-23 16:56  坦率  阅读(234)  评论(0)    收藏  举报