C++雙目運(yùn)算符+=的重載詳解
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、運(yùn)算符
3.1 單目運(yùn)算符
單目運(yùn)算符是指運(yùn)算所需變量為一個(gè)的運(yùn)算符。
邏輯非運(yùn)算符【!】、按位取反運(yùn)算符【~】、自增自減運(yùn)算符【++,–】、負(fù)號(hào)運(yùn)算符【-】
類型轉(zhuǎn)換運(yùn)算符【(類型)】、指針運(yùn)算符和取地址運(yùn)算符【*和&】、長度運(yùn)算符【sizeof】
3.2 雙目運(yùn)算符
雙目運(yùn)算符就是對(duì)兩個(gè)變量進(jìn)行操作。
初等運(yùn)算符
下標(biāo)運(yùn)算符【[]】、分量運(yùn)算符的指向結(jié)構(gòu)體成員運(yùn)算符【->】、結(jié)構(gòu)體成員運(yùn)算符【.】 算術(shù)運(yùn)算符
乘法運(yùn)算符【*】、除法運(yùn)算符【/】、取余運(yùn)算符【%】 、加法運(yùn)算符【+】、減法運(yùn)算符【-】
關(guān)系運(yùn)算符
等于運(yùn)算符【==】、不等于運(yùn)算符【!=】 、關(guān)系運(yùn)算符【< > <=> = 】
邏輯與運(yùn)算符【&&】、邏輯或運(yùn)算符【||】、邏輯非運(yùn)算符【!】
位運(yùn)算符
按位與運(yùn)算符【&】、按位異或運(yùn)算符【^】 、按位或運(yùn)算符【|】、左移動(dòng)運(yùn)算符【<<】、右移動(dòng)運(yùn)算符【>>】
賦值運(yùn)算符 賦值運(yùn)算符【= += -= *= /= %= >>= <<= &= |= ^=】 逗號(hào)運(yùn)算符 【,】
3.3 三目運(yùn)算符
對(duì)三個(gè)變量進(jìn)行操作;
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;
};
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
輸出1000以內(nèi)的素?cái)?shù)的算法(實(shí)例代碼)
本篇文章是對(duì)輸出1000以內(nèi)的素?cái)?shù)的算法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
采用C++實(shí)現(xiàn)區(qū)間圖著色問題(貪心算法)實(shí)例詳解
這篇文章主要介紹了采用C++實(shí)現(xiàn)區(qū)間圖著色問題(貪心算法),很經(jīng)典的算法問題,需要的朋友可以參考下2014-07-07
win10環(huán)境下vscode Linux C++開發(fā)代碼自動(dòng)提示配置(基于WSL)
C++實(shí)現(xiàn)LeetCode(75.顏色排序)
C語言中的時(shí)間函數(shù)clock()和time()你都了解嗎

