#include<iostream>
using namespace std;
class Complex
{public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
friend Complex operator+(Complex &c1,Complex &c2);
friend Complex operator-(Complex &c1,Complex &c2);
friend Complex operator*(Complex &c1,Complex &c2);
friend Complex operator/(Complex &c1,Complex &c2);
friend Complex operator*(const double &a,Complex &c2);
friend Complex operator*(Complex &c1,const double &a);
friend Complex operator-(Complex &c1);
void display();
private:
double real;
double imag;
};
//下面定义成员函数
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i"<<")"<<endl;
}
Complex operator+(Complex &c1,Complex &c2)
{
Complex c;
c.real=c1.real+c2.real;
c.imag=c1.imag+c2.imag;
return c;
}
Complex operator-(Complex &c1,Complex &c2)
{return Complex(c1.real-c2.real,c1.imag-c2.imag);}
Complex operator*(Complex &c1,Complex &c2)
{return Complex(c1.real*c2.real-c1.imag*c2.imag,c1.real*c2.imag+c1.imag*c2.real);}
//虚数乘法公式(a+bi)*(c+di) =ac+adi+bci+bd*i^2 =(ac-bd)+(ad+bc)i
Complex operator/(Complex &c1,Complex &c2)
{return
Complex((c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag),
(c1.imag*c2.real-c1.real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag));
}//虚数除法公式=(ac+bd)/(c^2+d^2)+(bc-ad)/(c^2+d^2)i
Complex operator*(const double &a,Complex &c2)
{
return Complex(a*c2.real,c2.imag*a);
}
Complex operator*(Complex &c1,const double &a)
{
return Complex(c1.real*a,c1.imag*a);
}
Complex operator-(Complex &c1)
{
return Complex(-c1.real,-c1.imag);
}
//下面定义用于测试的main()函数
int main()
{
Complex c1(3,4),c2(5,-10),c3;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
c3=c1+c2;
cout<<"c1+c2=";
c3.display();
c3=c1-c2;
cout<<"c1-c2=";
c3.display();
c3=c1*c2;
cout<<"c1*c2=";
c3.display();
c3=c1/c2;
cout<<"c1/c2=";
c3.display();
c3=2*c2;
cout<<"2*c2=";
c3.display();
c3=c1*3;
cout<<"c1*3=";
c3.display();
cout<<"c3=-c2=";
c3=-c2;
c3.display();
return 0;
}
照着葫芦画的瓢,差不多明白了,不过用起来还是不太熟练,有待继续练