程序代碼:
#includeusing namespace std; 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);//復數的除法 //重載<<運算符實現輸出復數 friend ostream& operator <<(ostream& output, Complex& c); //重載>>運算符實現輸入復數 friend istream& operator >>(istream& input, Complex& c); private: double real;//復數的實部 double imag;//復數的虛部 }; //復數的加法 Complex Complex::operator+(Complex &c2) { Complex c3; c3.real = real + c2.real; c3.imag = imag + c2.imag; return c3; } //復數的減法 Complex Complex::operator-(Complex &c2) { Complex c3; c3.real = real - c2.real; c3.imag = imag - c2.imag; return c3; } //復數的乘法 Complex Complex::operator*(Complex &c2) { Complex c3; c3.real = real*c2.real - imag * c2.imag; c3.imag = real*c2.imag + imag * c2.real; return c3; } //復數的除法 Complex Complex::operator/(Complex &c2) { Complex c3; c3.real = (real * c2.real + imag * c2.imag) / (c2.real*c2.real + c2.imag * c2.imag); c3.imag = (imag * c2.real - real * c2.imag) / (c2.real*c2.real + c2.imag * c2.imag); return c3; } //重載>>運算符實現輸入復數 istream& operator >>(istream& input, Complex& c) { int a, b; char sign, i; do { cout<<"請輸入一個復數,以(a+bi或a-bi)的形式輸入:"; input>>a>>sign>>b>>i; }while(!(('+' == sign || '-' == sign) && 'i' == i)); c.real = a; c.imag = ('+' == sign) ? b : -b; return input; } //重載<<運算符實現輸出復數 ostream& operator <<(ostream& output, Complex& c) { int num = c.imag; if(num>0) { output< >c1; cout<<"請輸入一個復數:"; cin>>c2; //打印第一個復數 cout<<"c1 = "; cout<
執行結果: