微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C++ 运算符重载

<span style=font-family: Arial,Helvetica,sans-serif;>#include <iostream></span>
using namespace std; class complex { public: // 带缺省值的构造函数 complex (double real = 0,double image = 0) :_real(real),_image(image) { cout<<complex (double real = 0,double image = 0)<<endl; } // 析构函数 ~complex() { cout<<~complex()<<endl; } // 拷贝构造函数 complex (const complex& d) :_image(d._image),_real(d._real) { cout<<complex (const complex& d)<<endl; } // 赋值运算符重载 complex& operator= (const complex& d) { cout<<operator= (const complex& d)<<endl; if (this != &d) { this->_real = d._real; this->_image = d._image; } return *this; } // 取地址运算符重载 complex* operator& () { cout<<operator&()<<endl; return this; } // const修饰的取地址运算符重载 const complex* operator& () const { cout<<operator&() const<<endl; return this; } void display() { cout<<real:<<_real<<--image:<<_image<<endl<<endl; } // 请实现下面的运算符重载! complex& operator++() //前置++ //返回当前对象本身 { cout<<operator++()<<endl; _reaL++; _image++; return *this; //可以立即体现出前置++的值 } complex operator++(int)//后置++ { cout<<operator++(int)<<endl; complex c = *this; this->_reaL++; this->_image++; return c; } complex& operator--() { cout<<operator--()<<endl; _real--; _image--; return *this; } complex operator--(int) //后置-- { cout<<operator--()<<endl; complex c = *this; this->_real--; this->_image--; return c; } complex operator+(const complex& c) { cout<<operator+(const complex& c)<<endl; return complex(_real+c._real,_image+c._image); } complex operator-(const complex& c) { cout<<operator-(const complex& c)<<endl; return complex(_real-c._real,_image-c._image); } complex& operator-=(const complex& c) { cout<<operator-=(const complex& c)<<endl; _real -= c._real; _image -= c._image; return *this; } complex& operator+=(const complex& c) { cout<<operator+=(const complex& c)<<endl; _real += c._real; _image += c._image; return *this; } complex operator*(const complex& c) { cout<<operator*(const complex& c)<<endl; return complex(_real*c._real-_image*c._image,c._image*_real+_image*c._real); } complex operator/(const complex& c) { cout<<operator/(const complex& c)<<endl; return complex((_real/c._real+_image*c._image)/(c,_real*c._real+c._image*c._image),(_image*c._real-_real*c._image)/(c,_real*c._real+c._image*c._image)); } private: double _real; double _image; };

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐