空指针访问成员函数:C++中空指针也可以调用成员函数,但要注意隐含的this指针,若用到this指针,需加以判断保证代码的健壮性
class person
{
public:
void showClassname()
{
cout<<"person class"<<endl;
}
void showPersonAge()
{
cout<<"age="<<m_age<<endl; //属性前都默认有一个this指针,表示当前对象的属性
//即cout<<"age="<<this->m_age<<endl;
}
int m_age;
};
void test1()
{
person * p=NULL;
p->showClassname();//函数中没有this指针,可正常调用
p->showPersonAge();//函数中隐藏了一个this指针,且p为空指针,未创建任何对象,两者将发生冲突
}
上述代码将产生错误:this是nullptr读取访问权限冲突
解决方法:
class person
{
public:
void showClassname()
{
cout<<"person class"<<endl;
}
void showPersonAge()
{
if(this == NULL) //提高了代码的健壮性
{
return;
}
cout<<"age="<<m_age<<endl;
}
int m_age;
};