类和对象-this指针

 错误示范:

#include<iostream>
#include<string>
using namespace std;
class person {
public:
	person()
	{

	}
	person(int age)
	{
		age = age;
	}
	int age;
};
void test01()
{
	person p1(18);
	cout << "p1的年龄为:" << p1.age << endl;
}
int main() 
{
	test01();	
}

 改正:

#include<iostream>
#include<string>
using namespace std;
class person {
public:
	person()
	{

	}
	person(int age)
	{
		this->age = age;//this指针指向 被调用的成员函数 所属的对象,即p1!!!
	}
	int age;
};
//解决名称冲突
void test01()
{
	person p1(18);
	cout << "p1的年龄为:" << p1.age << endl;
}
int main() 
{
	test01();	
}

可正常打印年龄

创建personAddAge()函数进行类加

#include<iostream>
#include<string>
using namespace std;
class person {
public:
	person()
	{

	}
	person(int age)
	{
		this->age = age;
	}
	void personAddAge(person& p)
	{
		this->age += p.age;
	}
	int age;

};
//返回对象本身用*this
void test02()
{
	person p1(10);
	person p2(10);
	p2.personAddAge(p1);
	cout << "p2.age: " <<p2.age << endl;
}
int main() 
{
	test02();
 }

 

返回对象本身用*this:

#include<iostream>
#include<string>
using namespace std;
class person {
public:
	person()
	{

	}
	person(int age)
	{
		this->age = age;
	}
	//如果你要返回本体,要做一个引用的返回 person&
//如果你要返回一个值的方式返回,一定是创建一个新的对象,
//如果是要一个引用的返回,不会创建新的对象,会一直返回p2
	person& personAddAge(person& p)
	{
		this->age += p.age;
		return *this;
	}
	int age;

};
//返回对象本身用*this
void test02()
{
	person p1(10);
	person p2(10);
//链式编程
	p2.personAddAge(p1).personAddAge(p1).personAddAge(p1);//返回的是p2,重新调用add累加

	cout << "p2.age: " <<p2.age << endl;
}
int main() 
{
	test02();
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值