运算符,操作符 重载
#include <iostream> using namespace std;
class people{
public:
int a;
int b;
people():a(0),b(0){};
people(int x,int y):a(x),b(y){};
people& operator+=(const people&); //返回值是*this
friend people operator-(const people&,const people&); //返回值是一个新的people对象
};
people& people::operator+=(const people& p){
this->a+=p.a;
this->b+=p.b;
return *this;
}
people operator-(const people& p1,const people& p2){
people p;
p.a=p1.a-p2.a;
p.b=p1.b-p2.b;
return p;
}
ostream& operator<<(ostream& os,const people& p){
os<<"a="<<p.a<<" b="<<p.b<<endl;
return os;//为了保证能够连接操作,返回值仍然是流。。
}
int main(){
people p1(1,1);
people p2(2,3);
people p3 = p2-p1;
cout<<p3;
return 0;
}
输出:a=1 b=2