+,-,*,/的重载和<<与>>的重载
#include<iostream.h>
class complex
{
public:
complex(){real=0;imag=0;}
complex(double r,double i){real=r;imag=i;}
complex operator +(complex &c2);
complex operator -(complex &c2);
complex operator *(complex &c2);
complex operator /(complex &c2);
complex operator ++();
complex operator --();
complex operator ++(int);
complex operator --(int);
friend ostream& operator<<(ostream&,complex&);
private:
double real;
double imag;
};
complex complex::operator +(complex &c2)
{
complex c1;
c1.real=real+c2.real;
c1.imag=imag+c2.imag;
return c1;
}
complex complex::operator -(complex &c2)
{
complex c1;
c1.real=real-c2.real;
c1.imag=imag-c2.imag;
return c1;
}
complex complex::operator *(complex &c2)
{ //(a+bi)(c+di)=(ac-bd)+(bc+ad)i。
complex c1;
double a,b,c,d;
a=real;
b=imag;
c=c2.real;
d=c2.imag;
c1.real=(a*c-b*d);
c1.imag=(b*c+a*d);
return c1;
}
complex complex::operator /(complex &c2)
{ //x=(ac+bd)/(c2+d2) y=(bc-ad)/(c^2+d^2)
complex c1;
double a,b,c,d;
a=real;
b=imag;
c=c2.real;
d=c2.imag;
c1.real=(a*c+b*d)/(c*c+d*d);
c1.imag=(b*c-a*d)/(c*c+d*d);
return c1;
}
complex complex::operator ++()
{
complex c1;
c1.real=real+1;
c1.imag=imag+1;
return c1;
}
complex complex::operator ++(int)
{
complex c1(*this);
complex c;
c.real=real+1;
c.imag=imag+1;
return c1;
}
complex complex::operator --(int)
{
complex c1(*this);
complex c;
c.real=real-1;
c.imag=imag-1;
return c1;
}
complex complex::operator --()
{
complex c1;
c1.real=real-1;
c1.imag=imag-1;
return c1;
}
ostream& operator<<(ostream &output,complex& c)
{output<<"("<<c.real<<","<<c.imag<<"i"<<")"<<endl;
return output;
}
int main()
{
complex c1(3,5);
complex c2(4,7);
complex c3,c4,c5,c6,c7,c8,c9,c10;
c3=c1+c2;
c4=c1-c2;
c5=c1*c2;
c6=c1/c2;
c7=++c1;
c8=--c1;
c9=c1++;
c10=c1--;
cout<<"c3=";cout<<c3;
cout<<"c4=";cout<<c4;
cout<<"c5=";cout<<c5;
cout<<"c6=";cout<<c6;
cout<<"c7=";cout<<c7;
cout<<"c8=";cout<<c8;
cout<<"c9=";cout<<c9;
cout<<"c10=";cout<<c10;
return 0;
}