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