实现运算符重载
#include <iostream>using namespace std;
class Person{friend const Person operator-(const Person &L,const Person &R);friend bool operator<(const Person &L,const Person &R);friend Person operator-=(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{
// Person temp;
// temp.a = a - R.a;
// temp.b = b - R.b;
// return temp;
// }// bool operator<(const Person &R)const{
// if(a < R.a && b < R.b){
// return true;
// }
// else{
// return false;
// }
// }// Person operator-=(const Person &R){
// a -= R.a;
// b -= R.b;
// return *this;
// }void show(){cout << "a=" << a << " b=" << b << endl;}
};const Person operator-(const Person &L,const Person &R){Person temp;temp.a = L.a - R.a;temp.b = L.b - R.b;return temp;
}bool operator<(const Person &L,const Person &R){if(L.a < R.a && L.b < R.b){return true;}else{return false;}
}Person operator-=(Person &L,const Person &R){L.a -= R.a;L.b -= R.b;return L;
}int main()
{Person s1(30,20);Person s2(10,10);Person s3 = s1 - s2;s3.show();if(s3 < s1){cout << "s3<s1" << endl;}s1 -= s3;s3.show();return 0;
}
思维导图