用到this指针要先判断,这样才能增加代码的健壮性
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
class A
{
public:
void f()
{
cout << "f" << endl;
}
void f1()
{
if(this==NULL)//防止传入空指针时报错
{
return;
}
cout << "a=" << a << endl;//this->a
//传入指针为空,空指针访问属性会出问题
cout << "f1" << endl;
}
int a;
};
void t1()
{
A *p = NULL;
p->f();
p->f1();
}
int main()
{
t1();
system("pause");
return 0;
}
因为传入指针为空,所以不继续执行下面的代码,不会报错。
成员函数f没有用到成员变量,空指针可以访问到。