- 空指针访问成员函数
1.如果 成员函数中没有用到this 则可以直接使用
2.如果成员函数中使用了this,则会出错,所以我们要在成员函数中添加空指针判断
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//如果用空指针访问成员函数
//1.如果 成员函数中没有用到this 则可以直接使用
//2.如果成员函数中使用了this,则会出错,所以我们要在成员函数中添加空指针判断
class person
{
public:
void func1()//没有用到this指针
{
cout << "func1被调用了" << endl;
}
void func2()//用到了this指针,所以要添加空指针判断语句
{
if (this == NULL)
{
cout << "this是一个空指针" << endl;
return;
}
this->m_a = 10;
cout << "func2被调用了" << endl;
}
int m_a;
};
int main()
{
person *p=NULL;
p->func1();
p->func2();
system("pause");
return EXIT_SUCCESS;
}