//运算符重载:
//赋予运算符新的作用
//注意事项:
//1、内置的数据类型的表达式的运算符不能改变
//2、不要滥用运算符
#include<iostream>
using namespace std;
class Person {
public:
int m_a;
int m_b;
//成员函数实现运算符重载
Person operator+(Person& p) {
Person tmp;
tmp.m_a = this->m_a + p.m_a;
tmp.m_b = this->m_b + p.m_b;
return tmp;
}
};/*
Person operator+(Person& p1, Person& p2) {
Person tmp;
tmp.m_a = p1.m_a + p2.m_a;
tmp.m_b = p1.m_b + p2.m_b;
return tmp;
}*/
Person operator+(Person& p, int num) {
Person tmp;
tmp.m_a = p.m_a +num;
tmp.m_b = p.m_b + num;
return tmp;
}
void test01() {
Person p1;
p1.m_a = 10;
p1.m_b = 10;
Person p2;
p2.m_a = 10;
p2.m_b = 10;
//本质是Person p3=p1.operator(p2);
Person p3 = p1 + p2;
cout << "p3,m_a=" << p3.m_a << endl;
cout << "p3,m_b=" << p3.m_b << endl;
//运算符重载也可以发生函数重载
Person p4 = p1 + 100;
cout << "p3,m_a=" << p4.m_a << endl;
cout << "p3,m_b=" << p4.m_b << endl;
}
int main() {
test01();
return 0;
}