1.this指针在程序中也会暗自被使用。
#include <iostream>
using namespace std;
class Person {
public:
Person(int a) {
mAge = a;
}
void ShowClassName() {
cout << "我是Person类!" << endl;
}
void ShowPerson() {
cout << mAge << endl;//相当于cout<<this->mAge<<endl;
//而this的指针是指向一个对象的,现在this是空指针,空指针去哪访问mAge?所以这里会爆错。
}
public:
int mAge = 100;
};
int main() {
Person* p=NULL;
p->ShowClassName(); //空指针,可以调用成员函数,
p->ShowPerson(); //但是如果成员函数中用到了this指针,就不可以了
}
报错界面如下图所示:
2.正确的使用方式。
我们在设计到指针指向的函数体中加一个if判断的语句,如果是空指针就退出,这样就可以避免程序爆错,让代码更加健壮。
#include <iostream>
using namespace std;
class Person {
public:
void ShowClassName() {
cout << "我是Person类!" << endl;
}
void ShowPerson() {
if (this == NULL) { //代码的健壮改进就体现在这里,加入了判断程序。
return;
}
cout << mAge << endl;//这里我们没有写this->,但是系统在编译的时候会给我们自动加进去,暗指其属于当前的对象。
}
public:
int mAge;
};
int main() {
Person* p = NULL;//这里没有定义对象,只是定义了一个person类型的指针叫p而已,但其不指向任何对象,他只时一个空指针。
p->ShowClassName(); //空指针,可以调用成员函数
p->ShowPerson(); //但是如果成员函数中用到了this指针,就不可以了
}
如何让指针不指向空对象?
只需构建一个实体对象,再让指针指向它即可。
```cpp
Person p1(10);
Person* p=&p1;//这时候指向的就不是空指针,而是一个有实体指向的指针
p->ShowClassName();
p->ShowPerson();