C++中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针
如果用到this指针,需要加以判断保证代码的健壮性
#include <iostream>#include <string>using namespace std;class Person{public:Person(int age) {this->m_age = age;}void showName() {cout << "Class name" << endl;}void showAge() {cout << "Age is " << this->m_age << endl;//若设置指针为空,则this为空指针,不指向任何值}int m_age;};void main() {Person* p;p = NULL;p->showName();p->showAge();//此时this指针和p为空指针,运行异常system("pause");}
为解决上述问题,可以在调用任何成员时判断this指针是否为空,如果为空则直接返回,这样可以增加代码的健壮性,令其适应更多场合,容错率更高。这种增加代码健壮性的行为和前面在析构函数中进行深拷贝的思想类似。
#include <iostream>#include <string>using namespace std;class Person{public:Person(int age) {this->m_age = age;}void showName() {cout << "Class name" << endl;}void showAge() {//这个函数调用了一个成员变量,那么需要对this指针进行判断;if (this == NULL) {return;}cout << "Age is " << this->m_age << endl;//若设置指针为空,则this为空指针,不指向任何值}int m_age;};void main() {Person* p;p = NULL;p->showName();p->showAge();//此时this指针和p为空指针,直接返回。system("pause");}
