// Complex 类的基本函数
#include<iostream> using namespace std; class Complex { public : Complex(double real=1.0,double image=2.0)//构造函数 (有参) 调用2次拷贝构造 { _real=real; _image=image; } Complex() //构造函数 (无参) { _real=1.0; _image=2.0; } 亦可写成: Complex(double real=1.0,double image=2.0)//构造函数 初始化列表进行初始化 :_real(real) // 调用1次拷贝构造 ,_image(image) {} Complex(const Complex& c)//拷贝构造函数 参数必须引用传参 { _real=c._real; _image=c._image; } ~Complex()//析构函数 无参数返回值 清理 { cout<<"~Complex()"<<endl; } Complex& opertator=(const Complex& c) //赋值运算符的重载 = { // 方法一: // 非 const 仅 ----> const if(this != &c) { _real=c._real; _image=c._image; } return *this; // 方法二: // if(this != &c) // { // swap(_real,c._real); // swap(_image,c._image); // } // return *this; } Complex& opertator+(const Complex& c) // + { Complex tmp; tmp._real=_real+c._real; tmp._image=_image+c._image; return tmp; } Complex& opertator-(const Complex& c) // - { Complex tmp; tmp._real=_real-c._real; tmp._image=_image-c._image; return tmp; } Complex operator*(Complex& c) // * { Complex tmp; tmp._real=_real*c._real; tmp._image=_image*c._image; return tmp; } Complex operator/(Complex& c) // / { Complex tmp; tmp._real=_real/c._real; tmp._image=_image/c._image; return tmp; } Complex& opertator++(int) // 后置++ { Complex tmp(*this); _real++; _image++; return tmp; //不能返回引用 } Complex& opertator++() // 前置++ { _real=_real+1; _image=_image+1; return *this; } Complex operator --(int) // 后置 -- { Complex tmp(*this); _real--; _image--; return tmp; } Complex& operator --() // 前置 -- { _real=_real-1; _image=_image-1; return *this; } public: bool operator>(const Complex& c) { return _real>c._real; return _image>c._image; } Complex* opertator&() { return *this; } protected : double _real ; double _image; }; 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; }
时间: 2024-10-20 07:59:50