作用:实现两个自定义数据类型相加的运算
#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
}