通过自己写成员函数,实现两个对象相加属性后返回新的对象
-
总结1:对于内置的数据类型的表达式的的运算符是不可能改变的(不修改内置函数)
-
总结2:不要滥用运算符重载(在加法运算符中写的是减法)
#include<iostream>
using namespace std;
class Person {
public:
int m_A;
int m_B;
Person() {};
Person(int a, int b)
{
this->m_A = a;
this->m_B = b;
}
//c成员函数实现+号运算符重载
Person operator+(const Person& p) {
Person temp;
temp.m_A = this->m_A + p.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& p1,int val) {
Person temp;
temp.m_A = p1.m_A + val;
temp.m_B = p1.m_B + val;
return temp;
}
void test() {
Person p1(10, 10);
Person p2(100, 10);
Person p3 = p2 + p1;
//Person p3 = p2.operator+(p1);
cout << "加法运算符重载:m_A." << p3.m_A << " 加法运算符重载:m_B" << p3.m_B << endl;
Person p4 = operator+(p3,10);
//Person p4 = p3 + 10;
cout << "m_A." << p4.m_A << "m_B" << p4.m_B << endl;
}
int main()
{
test();
return 0;
}