版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/XUCHEN1230/article/details/84974764
//空指针访问成员函数;
class Person
{
public:
void show()
{
cout << "Person show" << endl;
}
void showage()
{
cout << m_Age << endl;
}
int m_Age;
};
void test01()
{
Person * p = NULL;
p->show();
p->showage();
}
//可以调用show,不能调用showage。
//调用show时,编译器隐式加上了void show(Person * this)
//虽然此时this(==p)为空,但是下面的函数里没有用到this,所以没有影响;
//同理,对于showage(),里面是要用到this->m_Age的,但是其为空,所以会报错。
int main()
{
test01();
return 0;
}
可以加入if(!this)的保护措施。
//空指针访问成员函数;
class Person
{
public:
void show()
{
cout << "Person show" << endl;
}
void showage()
{
if (!this)//保护措施;
return;
cout << m_Age << endl;
}
int m_Age;
};
void test01()
{
Person * p = NULL;
p->show();
p->showage();
}
//可以调用show,不能调用showage。
//调用show时,编译器隐式加上了void show(Person * this)
//虽然此时this(==p)为空,但是下面的函数里没有用到this,所以没有影响;
//同理,对于showage(),里面是要用到this->m_Age的,但是其为空,所以会报错。
int main()
{
test01();
return 0;
}