对象的空指针

指向对象的空指针也可以访问对象成员,因此需要加判断this是否空来保证代码健壮性;

#include<iostream>
#include<string>
using namespace std;

class Person
{
public:
	int m_age;
	void ShowClassName()
	{
		cout << "this is  class Person!" << endl;
	}
	void ShowPersonName()
	{
		if (this == NULL)
		{
			return;
		}
		cout << "Person's name is" <<m_age<< endl;
	}
};
int main() 
{
	Person* p = NULL;
	p->ShowClassName();
	p->ShowPersonName();

	system("pause"); 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46432495/article/details/121758430