C++中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针。如果用到this指针,需要加以判断保证代码的健壮性。
例1:
#include<iostream>
using namespace std;
class person
{
public:
void show()
{
cout << m_Age << endl;//m_Age默认为this->m_Age
}
int m_Age;
};
int main()
{
person* p = NULL;
p->show();
system("pause");
return 0;
}
崩溃,因为这个this指针为空,无法访问m_Age。
因为在16行创建了一个person*的对象,并把他指向空,所以在9行的位置访问这个对象的m_Age就会崩溃。
例2:
#include<iostream>
using namespace std;
class person
{
public:
void show()
{
if (this == NULL)
{
return;
}
cout << m_Age << endl;//m_Age默认为this->m_Age
}
int m_Age;
};
int main()
{
person* p = NULL;
p->show();
system("pause");
return 0;
}
在9行加了一个判断语句,如果为空就直接返回,不会再访问m_Age,这样就不会崩溃了