#include <iostream>
using namespace std;
class Complex
{
public:
Complex(){real=0;imag=0;}
friend ostream& operator<< (ostream& output, Complex& c);
friend istream& operator>> (istream& input,Complex& c);
Complex(double r,double i){real=r; imag=i;}
Complex operator+(Complex &c2);
Complex operator-(Complex &c2);
Complex operator-();
Complex operator*(Complex &c2);
Complex operator/(Complex &c2);
void display();
private:
double real;
double imag;
};
//下面定义成员函数
ostream& operator<< (ostream& output, Complex& c)
{
output<<"("<<c.real;
if (c.imag>0)
output<<"+"<<c.imag<<"i)";
}
istream& operator>> (istream& input,Complex& c)
{
char ch;
input>>c.real>>ch;
if (ch!='-'||ch!='+')
{
cout<<"请输入+或者-"<<endl;
operator>> (input,c);
}
}
Complex Complex::operator-()
{
return -*this;
}
Complex Complex::operator+(Complex &c2)
{
Complex c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
Complex Complex::operator-(Complex &c2)
{
Complex c;
c.real=real-c2.real;
c.imag=imag-c2.imag;
return c;
}
Complex Complex::operator*(Complex &c2)
{
Complex c;
c.real=real*c2.real-imag*c2.imag;
c.imag=imag*c2.real+real*c2.imag;
return c;
}
Complex Complex::operator/(Complex &c2)
{
Complex c;
c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
c.imag=(imag*c2.real+real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
return c;
}
//下面定义用于测试的main()函数
int main()
{
Complex c1(3,4),c2(5,-10),c3;
cout<<"c1=";
cout<<c1<<endl;
cout<<"c2=";
cout<<c2<<endl;
c3=c1+c2;
cout<<"c1+c2=";
cout<<c3<<endl;
c3=c1-c2;
cout<<"c1-c2=";
cout<<c3<<endl;
c3=c1*c2;
cout<<"c1*c2=";
cout<<c3<<endl;
c3=c1/c2;
cout<<"c1/c2=";
cout<<c3<<endl;
return 0;
}