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

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

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
using namespace std;

class Person {
public:
void showClassName() { //无this
cout << "this is Person class" << endl;
}

void showPersonAge() { //有this
cout << "age = "<< this->m_Age <<endl;
}
int m_Age;
};

int main() {
Person* p = NULL;
p->showClassName();//正常
p->showPersonAge();//报错,因为传入指针为空(NULL)
return 0;
}

解决方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
using namespace std;

class Person {
public:
void showClassName() {
cout << "this is Person class" << endl;
}

void showPersonAge() {
if (this == NULL) {
return;
}
cout << "age = "<< this->m_Age <<endl;
}
int m_Age;
};

int main() {
Person* p = NULL;
p->showClassName();
p->showPersonAge();
return 0;
}