双目运算符+=的重载

时间:2021-01-01 02:14:00

双目运算符+=的重载

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