// Complex 类的基本函数
#include<iostream> using namespace std; class Complex { public : Complex(double real=1.0,double p_w_picpath=2.0)//构造函数 (有参) 调用2次拷贝构造 { _real=real; _p_w_picpath=p_w_picpath; } Complex() //构造函数 (无参) { _real=1.0; _p_w_picpath=2.0; } 亦可写成: Complex(double real=1.0,double p_w_picpath=2.0)//构造函数 初始化列表进行初始化 :_real(real) // 调用1次拷贝构造 ,_p_w_picpath(p_w_picpath) {} Complex(const Complex& c)//拷贝构造函数 参数必须引用传参 { _real=c._real; _p_w_picpath=c._p_w_picpath; } ~Complex()//析构函数 无参数返回值 清理 { cout<<"~Complex()"<<endl; } Complex& opertator=(const Complex& c) //赋值运算符的重载 = { // 方法一: // 非 const 仅 ----> const if(this != &c) { _real=c._real; _p_w_picpath=c._p_w_picpath; } return *this; // 方法二: // if(this != &c) // { // swap(_real,c._real); // swap(_p_w_picpath,c._p_w_picpath); // } // return *this; } Complex& opertator+(const Complex& c) // + { Complex tmp; tmp._real=_real+c._real; tmp._p_w_picpath=_p_w_picpath+c._p_w_picpath; return tmp; } Complex& opertator-(const Complex& c) // - { Complex tmp; tmp._real=_real-c._real; tmp._p_w_picpath=_p_w_picpath-c._p_w_picpath; return tmp; } Complex operator*(Complex& c) // * { Complex tmp; tmp._real=_real*c._real; tmp._p_w_picpath=_p_w_picpath*c._p_w_picpath; return tmp; } Complex operator/(Complex& c) // / { Complex tmp; tmp._real=_real/c._real; tmp._p_w_picpath=_p_w_picpath/c._p_w_picpath; return tmp; } Complex& opertator++(int) // 后置++ { Complex tmp(*this); _real++; _p_w_picpath++; return tmp; //不能返回引用 } Complex& opertator++() // 前置++ { _real=_real+1; _p_w_picpath=_p_w_picpath+1; return *this; } Complex operator --(int) // 后置 -- { Complex tmp(*this); _real--; _p_w_picpath--; return tmp; } Complex& operator --() // 前置 -- { _real=_real-1; _p_w_picpath=_p_w_picpath-1; return *this; } public: bool operator>(const Complex& c) { return _real>c._real; return _p_w_picpath>c._p_w_picpath; } Complex* opertator&() { return *this; } protected : double _real ; double _p_w_picpath; }; void Test1() { Complex c1(3.0,6.0); c1.Display1(); c1.Display2(); Complex c2(c1); c2.Display1(); c2.Display2(); Complex ret1=c1+c2; ret1.Display1(); Complex ret2=c1-c2; ret2.Display1(); Complex ret3=c1*c2; ret3.Display1(); Complex ret4=c1/c2; ret4.Display1(); (c1++).Display1(); (++c1).Display1(); (c1--).Display1(); (--c1).Display1(); (c1+=c2).Display1(); (c1-=c2).Display1(); } int main() { Test1(); return 0; }