C++双目运算符+=的重载详解

1、+=重载

```class Complex
{
public:
Complex(int a, int b)
: _a(a)
, _b(b)
{}
Complex& operator+= (Complex& other)
{
this->_a += other._a;
this->_b += other._b;
return *this;
}
void print()
{
cout << _a << endl;
cout << _b << endl;
}
private:
int _a;
int _b;
};
void TestLei()
{
int a = 10, b = 20, c = 30;
Complex c1(10, 20);
Complex c2(20, 30);
Complex c3(30, 40);
c1 += c2 += c3;
c1.print();
}
```

2、friend重载+=

```class Complex
{
public:
Complex(int a, int b)
: _a(a)
, _b(b)
{}
friend Complex& operator+= (Complex& c1, Complex& c2)
{
c1._a += c2._a;
c1._b += c2._b;
return c1;
}
void print()
{
cout << _a << endl;
cout << _b << endl;
}
private:
int _a;
int _b;
};
void TestFriend()
{
int a = 10, b = 20, c = 30;
Complex c1(10, 20);
Complex c2(20, 30);
Complex c3(30, 40);
c1 += c2 += c3;
c1.print();
}
```

3、运算符

3.3 三目运算符

```b ? x : y
```

4、重载++和重载- -

```class Test
{
public:
Test(int t = 0)
:_t(t)
{}
Test& operator++() // 前置++
{
++_t;
return *this;
}
Test operator++(int)// 后置++
{
Test temp = *this;
++_t;
return temp;
}
Test& operator--()// 前置--
{
--_t;
return *this;
}
Test operator--(int)// 后置--
{
Test temp = *this;
--_t;
return temp;
}
int Result()
{
return _t;
}
private:
int _t;
};
```