双目运算符+=的重载

来源:互联网 发布:sqlserver视频教程 编辑:程序博客网 时间:2024/04/27 20:03

双目运算符+=的重载

#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;     判断是否为const2.(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 0int 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();#endifint 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;}