46 C++ 加号运算符重载

 作用:实现两个自定义数据类型相加的运算

#include"cf_14.h"

class PersonM
{
public:
	PersonM() {}
	PersonM(int a, int b)
	{
		this->A = a;
		this->B = b;
	}

	// 方法1:成员函数实现加号运算符重载
	PersonM operator + (const PersonM&p)
	{
		PersonM temp;
		temp.A = this->A + p.A;
		temp.A = this->B + p.B;
		return temp;
	}
	int A;
	int B;
};


// 方法2:全局函数实现加号运算符重载
PersonM operator+(const PersonM& p1, const PersonM& p2)
{
	PersonM temp;
	temp.A = p1.A + p2.A;
	temp.B = p1.B + p2.B;
	return temp;
}
// 方法3:
PersonM operator+(const PersonM& p1, int p2)
{
	PersonM temp;
	temp.A = p1.A + p2;
	temp.B = p1.B + p2;
	return temp;
}

void cf_14_test_01()
{
	// 方法1
	PersonM p6;
	p6.A = 3;
	p6.B = 3;
	PersonM p7;
	p7.A = 1;
	p7.B = 1;
	PersonM p8 = p6.operator+(p7);// 本质写法
	cout << "p8.A:" << p8.A << endl;
	cout << "p8.B:" << p8.B << endl;
	PersonM p9 = p6 + p7;// 简化写法
	cout << "p9.A:" << p9.A << endl;
	cout << "p9.B:" << p9.B << endl;

	// 方法2
	PersonM p1(1, 1);
	PersonM p2(1, 1);
	PersonM p3;
	p3 = p1 + p2;
	cout << "p3.A:" << p3.A << endl;
	cout << "p3.B:" << p3.B << endl;

	//方法3
	PersonM p4;
	p4 = p3 + 10;
	cout << "p4.A:" << p4.A << endl;
	cout << "p4.B:" << p4.B << endl;

	// 使用方法1需要注释掉方法2和方法3
	// 使用方法2或方法3需要注释掉方法1



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值