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.1 單目運算符
單目運算符是指運算所需變量為一個的運算符。
邏輯非運算符【!】、按位取反運算符【~】、自增自減運算符【++,–】、負號運算符【-】
類型轉換運算符【(類型)】、指針運算符和取地址運算符【*和&】、長度運算符【sizeof】
3.2 雙目運算符
雙目運算符就是對兩個變量進行操作。
初等運算符
下標運算符【[]】、分量運算符的指向結構體成員運算符【->】、結構體成員運算符【.】 算術運算符
乘法運算符【*】、除法運算符【/】、取余運算符【%】 、加法運算符【+】、減法運算符【-】
關系運算符
等于運算符【==】、不等于運算符【!=】 、關系運算符【< > <=> = 】
邏輯與運算符【&&】、邏輯或運算符【||】、邏輯非運算符【!】
位運算符
按位與運算符【&】、按位異或運算符【^】 、按位或運算符【|】、左移動運算符【<<】、右移動運算符【>>】
賦值運算符 賦值運算符【= += -= *= /= %= >>= <<= &= |= ^=】 逗號運算符 【,】
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;
};
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!

