成员函数版本实现算术运算符的重载
全局函数版本实现算术运算符的重载
#include <iostream>
using namespace std;
class Person
{
friend const Person operator-(const Person &L,const Person &R);
private:
int a;
int b;
public:
Person() {}
Person(int a,int b):a(a),b(b){}
//成员函数实现运算符+重载
const Person operator+(const Person &R) const //L+R
{
Person temp;
temp.a = a + R.a;
temp.b = b + R.b;
return temp;
}
void show()
{
cout << "a = " << a << " b = " << b << endl;
}
};
//全局函数实现运算符-重载
const Person operator-(const Person &L,const Person &R) //L-R
{
Person temp;
temp.a = L.a - R.a;
temp.b = L.b - R.b;
return temp;
}
int main()
{
Person p1(1,2);
Person p2(2,1);
Person p3 = p1.operator+(p2); //+重载
p3.show();
Person p4 = operator-(p1,p2); //-重载
p4.show();
return 0;
思维导图