實現一個 Complex 類,支持:
+ - * / += -=++ --Display()#includeusing namespace std; class Complex { public: // 構造函數:缺省參數覆蓋所有情況 Complex(double real = 1.0, double image = 1.0) : _real(real), _image(image) {} // 拷貝構造 Complex(const Complex& other) : _real(other._real), _image(other._image) {} // 析構函數 ~Complex() {} // 賦值運算符 Complex& operator=(const Complex& other) { if (this != &other) { _real = other._real; _image = other._image; } return *this; } // 前置 ++ Complex& operator++() { ++_real; ++_image; return *this; } // 後置 ++ (int 佔位符) Complex operator++(int) { Complex tmp(*this); ++_real; ++_image; return tmp; } // 前置 -- Complex& operator--() { --_real; --_image; return *this; } // 後置 -- Complex operator--(int) { Complex tmp(*this); --_real; --_image; return tmp; } // 算術運算符 Complex operator+(const Complex& c) const { return Complex(_real + c._real, _image + c._image); } Complex operator-(const Complex& c) const { return Complex(_real - c._real, _image - c._image); } Complex operator*(const Complex& c) const { // (a+bi)(c+di) = (ac-bd) + (ad+bc)i return Complex(_real*c._real - _image*c._image, _real*c._image + _image*c._real); } Complex operator/(const Complex& c) const { // (a+bi)/(c+di) = (ac+bd)/(c²+d²) + (bc-ad)/(c²+d²)i double denom = c._real*c._real + c._image*c._image; return Complex((_real*c._real + _image*c._image) / denom, (_image*c._real - _real*c._image) / denom); } // 複合賦值 Complex& operator+=(const Complex& c) { _real += c._real; _image += c._image; return *this; } Complex& operator-=(const Complex& c) { _real -= c._real; _image -= c._image; return *this; } void Display() const { cout << "real:" << _real << " image:" << _image << endl; } private: double _real; double _image; }; // 測試 void Test1() { Complex a, b; a.Display(); // 1+1i Complex c = ++a; // 前置++ c.Display(); // 2+2i Complex d = b++; // 後置++ d.Display(); // 1+1i (b 變為 2+2i) a = a + b; a.Display(); // 4+4i } void Test2() { Complex a(1,2), b(3,4); a -= b; // -2-2i a.Display(); } int main() { Test2(); system("pause"); return 0; }
| 特性 | 實現要點 |
|---|---|
| 構造函數 | 用缺省參數 Complex(double=1.0, double=1.0) 統一處理無參/單參/雙參 |
| 拷貝構造 | 初始化列表直接複製成員,避免默認逐位拷貝(雖本類無指針也無害) |
| 運算符重載 | 二元運算符回傳新對象(const 成員函數),複合賦值回傳 *this 引用 |
| 前置/後置 | 後置版多一個 int 佔位參數,先拷貝舊值,再修改自身,返回舊值拷貝 |
| 除法公式 | 分母有理化:(a+bi)/(c+di) = (ac+bd)/(c²+d²) + (bc-ad)/(c²+d²)i |
本例展示了 C++ 類設計的核心要素:構造/拷貝/析構/賦值「四大函數」、運算符重載規範(常量正確性、返回值類型)、前後置自增區別。初學者可作為模板擴展為矩陣、向量等數學類。