C++ this指针

this指针

  • 解决名称冲突
  • 隐式加在每个成员函数中
  • this指针 指向 被调用的成员函数 所属的对象
  • *this 就是本体,代表的person对象本身
class Person
{
public:
	Person(int age)
	{
		//用途1 :解决名称冲突
		this->age = age;
	}


	//this指针 隐式加在每个成员函数中
	bool compareAge(Person &p)
	{
		if (this->age == p.age)
		{
			return true;
		}
		return false;
	}


	//返回调用对象本身的引用,便于链式编程
	//若返回person对象,使用的是值传递,在返回时会通过值传递的方式,返回新建对象
	Person&  personAddPerson(Person &p)
	{
		this->age += p.age;
		return *this; //*this 就是本体,代表的person对象本身
	}

	int age;
};

void test()
{
	//this指针 指向 被调用的成员函数 所属的对象
	Person p1(10);

	cout << "p1的年龄为: " << p1.age << endl;


	Person p2(10);

	bool ret = p1.compareAge(p2);
	if (ret)
	{
		cout << "p1与p2年龄相等" << endl;
	}

	//链式编程
	p1.personAddPerson(p2).personAddPerson(p2).personAddPerson(p2); 
	cout << "p1的年龄为: " << p1.age << endl;

}

空指针访问成员函数

  • 如果成员函数中没有用到this指针,可以用空指针调用成员函数
  • 如果成员函数中用到了this,那么这个this需要加判断,防止代码down掉

class Person
{
public:

	void showClass()
	{
		cout << "class Name is Person" << endl;
	}

	void showAge()
	{
		//防止空指针访问成员变量,空指针不没有成员变量,调用会出错
		if (this == NULL)
		{
			return;
		}	
		cout << "age = " << this->m_Age << endl;
	}

	int m_Age;
};


void test01()
{
	//空指针
	Person * p = NULL;
	
	//未使用this指针可以正常调用
	p->showClass();

	p->showAge();

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值