c++ 运算符重载:+

#include<iostream>
using namespace std;
#include <string>
class Person {
public:
	int m_A;
	int m_B;
	Person() {};
	Person(int a ,int b) {
		this->m_A = a;
		this->m_B = b;//this指代引用的那个元素,把接收来的a,b赋值给该元素
	}
	//成员函数实现+号运算符重载
	Person operator+(const Person& p) {//首先 重载 是允许存在多个同名函数 这些函数的参数不同传入的函数也不同 
	//其次 加const是因为 我们不希望在这个函数中对用来进行赋值的原版做修改 而& 会导致传入的数据原版被修改 函数加上const后缀的作用是表面函数本身不会修改类成员变量
		//加上const 对于const和非const的实参函数都能接受 如果不加就只能接受非const实参
		//另外 那为什么我们还要用&?这样可以避免调用时对实参的一次拷贝 提高了效率
		Person temp;//中间人
		temp.m_A = this->m_A + p.m_A;//调用的m_A 加上传入的m_A
		temp.m_B = this->m_B + p.m_B;
		return temp;
	}
};
//全局函数实现 + 号运算符重载
//Person operator+(const Person& p1, const Person& p2) {
//	Person temp(0, 0);
//	temp.m_A = p1.m_A + p2.m_A;
//	temp.m_B = p1.m_B + p2.m_B;
//	return temp;
//}

//运算符重载 可以发生函数重载 
Person operator+(const Person& p2, int val)
{
	Person temp;
	temp.m_A = p2.m_A + val;
	temp.m_B = p2.m_B + val;
	return temp;
}
void test() {
	Person p1(10,10);
	Person p2(10,20);
	Person p3 = p2 + p1;//相当于p2.operator+(p1) 调用的成员函数实现的那个
	cout << "mA:" << p3.m_A << "mB:" << p3.m_B << endl;
	Person p4 = p3 + 20;//相当于operator+(p3+20) 调用的第二个
	cout << "mA:" << p4.m_A << "mB:" << p4.m_B << endl;

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

> 总结1:对于内置的数据类型的表达式的的运算符是不可能改变的

> 总结2:不要滥用运算符重载

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值