复现complex类(持续更新)
2021/1/13
#ifndef __MYCOMPLEX__ #define __MYCOMPLEX__ class mycomplex; mycomplex& __doapl(mycomplex* ths, const mycomplex& r); class mycomplex { public: mycomplex (double r = 0 , double i = 0) :re(r),im(i){} mycomplex& operator += (const mycomplex&); double real() const { return re; } double imag() const { return im; } private: double re, im; friend mycomplex& __doapl(mycomplex*, const mycomplex&); }; inline mycomplex& __doapl(mycomplex * ths, const mycomplex& r) { ths->re += r.re; ths->im += r.im; return *ths; } inline mycomplex& mycomplex::operator += (const mycomplex& r) { return __doapl(this, r); } inline double imag(const mycomplex& x) { return x.imag(); } inline double real(const mycomplex& x) { return x.real(); } // 为什么 重载+ 不设为成员函数,因为不仅仅要考虑到 complex对象 + complex对象,也要考虑到 实数 + complex对象 和 complex对象 + 实数。 inline mycomplex operator + (const mycomplex& x, const mycomplex& y) { return mycomplex(real(x) + real(y), imag(x) + imag(y)); } inline mycomplex operator + (double x, const mycomplex& y) { return mycomplex(x+real(y), imag(y)); } inline mycomplex operator + (const mycomplex& x, double y) { return mycomplex(real(x) + y, imag(x)); } #endif