双目运算符重载
#include <iostream>
using namespace std;
class complex
{
public:
complex():real(0),imag(0){};
complex(int r,int i):real(r),imag(i){};
~complex(){}
void display();
friend complex operator+(const complex&c1,const complex&c2);
friend complex operator+(const complex&c1,const int i);
friend complex operator+(const int i,const complex&c1);
private:
int real;
int imag;
};
void complex::display()
{
cout<<"("<<real<<","<<imag<<")";
}
complex operator+(const complex&c1,const complex&c2)
{
complex temp;
temp.real=c1.real+c2.real;
temp.imag=c1.imag+c2.imag;
return temp;
}
complex operator+(const complex&c1,const int i)
{
complex temp;
temp.real=c1.real+i;
temp.imag=c1.imag;
return temp;
}
complex operator+(const int i,const complex&c1)
{
complex temp;
temp.real=c1.real+i;
temp.imag=c1.imag;
return temp;
}
int main()
{
complex t1(1,2),t2(0,1),c1,c2,c3;
c1=t1+t2;
c1.display();
c2=t1+1;
c2.display();
c3=1+t1;
c3.display();
}
结果
