空指针访问成员函数

空指针访问成员函数

  • c++中空指针可以调用成员函数,但是要注意有没有用到this指针
  • 如果要用到this指针,需要加以判断保证代码的健壮性

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
using namespace std;
class Person {
public:
int m_Age;
void showClassName() {
cout << "this is Person class" << endl;
}

void showPersonAge1() {
if (this == NULL) {//空指针判断
return;
}
cout << "age = " << m_Age << endl;
}
void showPersonAge() {
cout << "age = " << m_Age << endl;
//等价于 cout << "age = " << this.m_Age << endl;
}
};
void test02() {
Person* p;
p->showClassName();
//报错原因是传入的指针是NULL
//p->showPersonAge();
p->showPersonAge1();
}
int main() {
test02();
return 0;
}