1 //设计运算符重载的复数类 2 #include<iostream.h> 3 4 class Complex{ 5 private: 6 double real;//实部 7 double image;//虚部 8 public: 9 Complex(){ 10 real=0; 11 image=0; 12 } 13 Complex(double real){ 14 this->real=real; 15 image=0; 16 } 17 Complex(double real,double image){ 18 this->real=real; 19 this->image=image; 20 } 21 ~Complex(){} 22 23 Complex operator+(const Complex &x)const; 24 Complex operator-(const Complex &x)const; 25 Complex operator*(const Complex &x)const; 26 Complex operator/(const Complex &x)const; 27 bool operator==(const Complex &x)const; 28 Complex &operator+=(const Complex &x); 29 void Print(); 30 }; 31 32 inline Complex Complex::operator+(const Complex &x)const{ 33 return Complex(this->real+x.real,this->image+x.image); 34 } 35 36 inline Complex Complex::operator-(const Complex &x)const{ 37 return Complex(this->real-x.real,this->image-x.image); 38 } 39 40 inline Complex Complex::operator*(const Complex &x)const{ 41 return Complex(this->real*x.real-this->image*x.image,this->real*x.image+this->image*x.real); 42 } 43 44 inline Complex Complex::operator/(const Complex &x)const{ 45 double m; 46 m=x.real*x.real+x.image*x.image; 47 return Complex((this->real*x.real+this->image*x.image)/m,(this->image*x.real-this->real*x.image)/m); 48 } 49 50 inline bool Complex::operator==(const Complex &x)const{ 51 return bool(this->real==x.real&&this->image==x.image); 52 } 53 54 Complex &Complex::operator+=(const Complex &x){ 55 this->real+=x.real; 56 this->image+=x.image; 57 return *this; 58 } 59 void Complex::Print(){ 60 cout<<"("<<this->real<<","<<this->image<<"i)"<<endl; 61 } 62 63 int main(){ 64 Complex a(3,5),b(2,3),c; 65 c=a+(b*a)/b-b; 66 c.Print(); 67 68 //a=a/b; 69 // a.Print(); 70 return 0; 71 }