空指针访问成员函数问题

空指针访问成员函数问题

先看一段代码,分析结果:

#include<iostream>
using namespace std;
class Person{
public:
	void show(){
		cout << "Person show" << endl;
	}
	void showAge(){
		cout << this->m_Age << endl; 
	}
	
	int m_Age; 
};

void test01(){
	Person * p = NULL;
	p->show();
	p->showAge();
}

int main(){
	test01();
	return EXIT_SUCCESS;
}

如果把p->showAge();注释掉,程序是可以正常运行的,结果为打印"Person show"
但是为什么加上p->showAge();之后,程序运行就会崩溃呢?
原因是C++会在成员函数里隐含加上this指针,也就是代码如下:

#include<iostream>
using namespace std;
class Person{
public:
	void show(Person* this){
		cout << "Person show" << endl;
	}
	void showAge(Person* this){
		cout << this->m_Age << endl; //NULL -> m_Age
	}
	
	int m_Age; 
};

void test01(){
	Person * p = NULL;
	p->show();
	p->showAge();
}

int main(){
	test01();
	return EXIT_SUCCESS;
}

show函数内,没有用到this对象,仅仅提供打印功能,所以没有报错,但是showAge函数内,用到了this对象的成员函数,由于Person * p = NULL;则访问空的成员就会报错。

我们常常在成员函数里加上判空检查,来保证代码的鲁棒性:

#include<iostream>
using namespace std;
class Person{
public:
	void show(){
		cout << "Person show" << endl;
	}
	void showAge(){
		if (this == NULL){
			return;
		}
		cout << this->m_Age << endl; 
	}
	
	int m_Age; 
};

void test01(){
	Person * p = NULL;
	p->show();
	p->showAge();
}

int main(){
	test01();
	return EXIT_SUCCESS;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值