复数的概念我们高中已经接触过,包含是实部和虚部,
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函数里测试,可以单独封装一个函数进行测试)
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; }
时间: 2024-12-26 04:48:50