加号+运算符重载

本文详细介绍了C++中运算符重载的概念,通过具体的Person类实例,演示了如何使用成员函数和全局函数两种方式来重载加号运算符,实现两个对象的属性相加。比较了不同实现方式的特点,帮助读者理解并掌握运算符重载的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
using namespace std;

//实现	对象3 = 对象1 + 对象2
//1普通实现方式
//1.1成员函数方式
//1.2全局函数方式

//2加号重载方式
//2.1成员函数加号重载方式
//2.2全局函数加号重载方式

class Person
{
public:
	int m_A;
	int m_B;

	//Person personAddPerson(Person &k)	//1.1成员函数方式
	//{
	//	Person temp;
	//	temp.m_A = this->m_A + k.m_A;
	//	temp.m_B = this->m_B + k.m_B;
	//	return temp;
	//}

	//Person operator+(Person &k)		//2.1成员函数加号重载方式
	//{
	//	Person temp;
	//	temp.m_A = this->m_A + k.m_A;
	//	temp.m_B = this->m_B + k.m_B;
	//	return temp;
	//}
};

//Person perAper(Person &x, Person &y)		//1.2全局函数方式
//{
//	Person temp;
//	temp.m_A = x.m_A + y.m_A;
//	temp.m_B = x.m_B + y.m_B;
//	return temp;
//}

Person	operator+(Person &x,Person &y)		//2.2全局函数加号重载方式
{
	Person temp;
	temp.m_A = x.m_A + y.m_A;
	temp.m_B = x.m_B + y.m_B;
	return temp;
}

void test01()
{
	Person p;
	p.m_A = 10;
	p.m_B = 10;

	Person p1;
	p1.m_A = 10;
	p1.m_B = 10;

	Person p2;
	//p2 = p.personAddPerson(p1);			//1.1成员函数方式
	//p2 = perAper(p, p1);		//1.2全局函数方式
	//p2 = p + p1;		//2.1.成员函数加号重载方式  相当于p2=p.operator+(p1);
	p2 = p + p1;		//2.2全局函数加号重载方式	相当于p2=operator+(p, p1);
	cout << "p2.m_A = " << p2.m_A << endl;
	cout << "p2.m_B = " << p2.m_B << endl;

}

int main()
{
	test01();
	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值