运算符重载

注意:重载用到ostream时,不能将ostream对象设为const常量,因为此类的成员需要对其他ostream类的方法进行操作。
重载加号:

 Complex operator+(const Complex& A, const Complex& B) {
	 Complex c;
	c.m_x = B.m_x + A.m_x;
	c.m_y = B.m_y + A.m_y;
	return c;

}

<<

ostream& operator<<( ostream& out, const Complex& A) {//重载<<运算符
	
	out <<"[" <<A.m_x << ","<<A.m_y<<"]";
	
	return out;
	
}

前置++和后置++

Complex Complex::operator++() {//前置
	 this->m_x++;
	 this->m_y++;
	 return *this;
 }

 ~~Complex Complex::operator++(int x) {//错误的后置
	 Complex tmp = *this;
	 tmp.m_x++;   		//此处应该是this->m_x++; this->m_y++;
	 tmp.m_y++;
	 return tmp;
 }~~ 
 

```cpp
Complex Complex::operator++(int x) {//正确的后置
	 Complex tmp = *this;
	 m_x++;
	 m_y++;
	 return tmp;
 }
重载+=

```cpp
Complex Complex::operator+=(const Complex& c) {
	 this->m_x += c.m_x;
	 this->m_y += c.m_y;
	 return *this;
 }

测试代码:

#include<iostream>
using namespace std;
#include"Complex.h"
int main() {
	Complex c1(10), c2(20, 10);
	cout << c1 << "+" << c2 << "=" << c1 + c2 << endl;
	cout << (c1 += c2) << endl;
	cout << c1++ << endl;
	cout << ++c1 << endl;
	return 0;
	return 0;
}

错误的运行:
在这里插入图片描述
正确的运行结果为:
在这里插入图片描述
当我使用错误的重载时,用int型变量进行自增时也会错误。如下:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值