複數的概念咱們高中已經接觸過,包含是實部和虛部,ide
For example:2i + 3J;實部和虛部值可爲整型,亦可浮點型,那在此實現一下簡單的複數類的操做函數
代碼以下:測試
class Complex { public: Complex(double real,double imag) { _real = real; _imag = imag; } Complex(const Complex& c) { _real = c._real; _imag = c._imag; } ~Complex() { } Complex& operator=(const Complex& c) { if(&c != this) { this->_real = c._real; this->_imag = c._imag; } return *this; } Complex operator+(const Complex& c) { Complex ret(*this);// + 運算返回運算後的值 ret._real += c._real; ret._imag += c._imag; return ret; } Complex& operator++() // 前置++ , 當外面須要此返回值時,須要加& { this->_real += 1; this->_imag += 1; return *this; } Complex operator++(int) // 後置++ ,當外面不須要此返回值時,無需加& { Complex tmp(*this);//後置++返回原來的值,故定義一個臨時變量保存起來 this->_real += 1; this->_imag += 1; return tmp; } Complex& operator+= (const Complex& c) { this->_real = this->_real + c._real; this->_imag = this->_imag + c._imag; return *this; } inline bool operator==(const Complex& c) { return (_real == c._real && _imag == c._imag); } inline bool operator>(const Complex& c) { return (_real > c._real && _imag > c._imag); } inline bool operator>=(const Complex& c) { //return (_real >= c._real // && _imag >= c._imag); return (*this > c) || (*this == c);//直接使用上面實現重載符 > 和 == } inline bool operator<=(const Complex& c) { //return (_real <= c._real // && _imag <= c._imag); return !(*this > c);//直接使用上面實現重載符 > } bool operator<(const Complex& c) { return !(*this > c) || (*this == c);//直接使用上面實現重載符 >= } inline void Display() { cout<<_real<<"-"<<_imag<<endl; } private: double _real; double _imag; };
測試單元:(偷懶就在main函數裏測試,能夠單獨封裝一個函數進行測試)this
int main() { Complex c(1,2); Complex c1(c); //c1.Display(); //Complex ret = ++c1; //Complex ret = c1++; //ret.Display(); Complex ret(c1); ret.Display(); return 0; }