0
点赞
收藏
分享

微信扫一扫

肆-拾陆|this指针的使用

潇湘落木life 2022-04-16 阅读 51
c++
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//谁在调用这个函数,this指针指向谁
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&  personAddPerson(Person &p)
	{
		this->age += p.age;
		return *this; //*this 就是本体
	}

	int age;
};

void test01()
{
	//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); //链式编程
	//第一次调用的时候加了10,但第一次返回虽然是他的本体,但用值的方式返回,会拷贝构造出一个新的本体。
	//后面再做函数调用已经不是对p1进行操作
	//返回值会返回一个副本,返回引用才会返回本身。
	cout << "p1的年龄为 " << p1.age << endl;

}


int main(){

	test01();

	system("pause");
	return EXIT_SUCCESS;
}
举报

相关推荐

0 条评论