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;
};

波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!

波比源码 » C++ 运算符重载

发表评论

Hi, 如果你对这款模板有疑问,可以跟我联系哦!

联系站长
赞助VIP 享更多特权,建议使用 QQ 登录
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡