双目运算符+=的重载

双目运算符+=的重载

#include "stdafx.h"
#include <iostream>
using namespace std;


#if 0

通常情况下:

单目 :
重载为成员的话,需要0个参数,重载为友元的时候需要一个参数


双目(+)
重载为成员的话,需要一个参数,重载为友元的时候需要俩个参数

friend Complex operator+(Complex &a, Complex &b);
//operator+(a,b);

const Complex operator+(Complex & another);
//a.operator+(b);
//成员的话 当中自己包含一个this 所以只需要一个参数

三目没有重载

进行+=的重载主要判断俩种情况:
1.a += b += c;     判断是否为const
2.(a += b) += c;   判断是否加&

#endif 



//双目运算符+=的重载

class Complex
{
public:
	Complex(float x = 0, float y = 0)
		:_x(x), _y(y){}
	void dis()
	{
		cout << "(" << _x << "," << _y << ")" << endl;
	}

	Complex & operator+=(const Complex &another);

private:
	float _x;
	float _y;
};


Complex& Complex::operator+=(const Complex &another)
{
	this->_x += another._x;
	this->_y += another._y;
	return *this;
}



int _tmain(int argc, _TCHAR* argv[])
{

#if 0
	int a = 10, b = 20, c = 30;
	a += b;
	b += c;
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;

	cout << "==============================" << endl;

	Complex x(10, 0), y(20, 0), z(30, 0);
	x += y;
	y += z;

	x.dis();
	y.dis();
	z.dis();
	------------------ -
		int a = 10, b = 20, c = 30;
	a += b += c;
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;

	cout << "==============================" << endl;

	Complex x(10, 0), y(20, 0), z(30, 0);
	x += y += z;

	x.dis();
	y.dis();
	z.dis();
#endif

	int a = 10, b = 20, c = 30;
	(a += b) += c;  //判断需不需要加&
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;

	cout << "==============================" << endl;

	Complex x(10, 0), y(20, 0), z(30, 0);
	(x += y) += z;

	x.dis();
	y.dis();
	z.dis();

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值