運算子過載——過載+和-對複數類物件進行加減運算
阿新 • • 發佈:2019-02-19
1.題目:
Problem Description
定義一個複數類,該類包含兩個double型的資料成員代表複數的實部和虛部,包含建構函式(預設值為0,0),和顯示函式,現過載運算子+和-,使其能對複數類物件進行加和減運算。在主函式中進行測試Input
輸入資料有多行,每行包括4個數,前兩個代表參與運算的第一個複數物件的實部和虛部,後兩個代表第二個複數物件的實部和虛部。Output
輸出多行,每行包括了加和減運算後的結果。複數按a+bi或a-bi格式顯示,按數學課本中的要求顯示。
Sample Input
100 20 -10 18
2 2 2 4
Sample Output
90+38i 110+2i 4+6i -2i
2.想法:
這道題目主要是要考慮輸出時的集中特殊情況,有實部和虛部都為0,還有虛部為1,-1,整數,負數的情況。靜下心來其實不難的。
3.參考程式碼一:
#include <iostream> using namespace std; class Complex { private: double real, image; public: Complex(double r = 0, double i = 0); Complex operator+(Complex&); Complex operator-(Complex&); void show(); }; Complex::Complex(double r, double i) { real = r; image = i; } Complex Complex::operator+(Complex& c) { Complex x; x.real = real + c.real; x.image = image + c.image; return x; } Complex Complex::operator-(Complex& c) { Complex x; x.real = real - c.real; x.image = image - c.image; return x; } void Complex::show() { if (real == 0) { if (image == 0) cout << 0; else if (image == 1) cout << "i"; else if (image == -1) cout << "-i"; else if (image > 0) cout << image << "i"; else if (image < 0) cout << image << "i"; } else { if (image == 0) cout << real; else if (image == 1) cout << real << "+i"; else if (image == -1) cout << real << "-i"; else if (image > 0) cout << real << "+" << image << "i"; else if (image < 0) cout << real << image << "i"; } } int main() { double a, b, c, d; while (cin >> a >> b >> c >> d) { Complex x(a, b), y(c, d), z, w; z = x + y; z.show(); cout << " "; w = x - y; w.show(); cout << endl; } return 0; }
參考程式碼二:
#include <iostream> using namespace std; class Complex { private: double real, image; public: Complex(double r = 0, double i = 0); Complex& operator+(Complex&); Complex& operator-(Complex&); void show(); }; Complex::Complex(double r, double i) { real = r; image = i; } Complex& Complex::operator+(Complex& c) { Complex x; x.real = real + c.real; x.image = image + c.image; return x; } Complex& Complex::operator-(Complex& c) { Complex x; x.real = real - c.real; x.image = image - c.image; return x; } void Complex::show() { if (image == 0) { if (real == 0) cout << "0"; else cout << real; } else if (image == 1) { if (real == 0) cout << "i"; else cout << real << "+i"; } else if (image == -1) { if (real == 0) cout << "-i"; else cout << real << "-i"; } else { if (real == 0) cout << image << "i"; else { if (image > 0) cout << real << "+" << image << "i"; else cout << real << image << "i"; } } } int main() { double a, b, c, d; while (cin >> a >> b >> c >> d) { Complex x(a, b), y(c, d), z, w; z = x + y; z.show(); cout << " "; w = x - y; w.show(); cout << endl; } return 0; }