【C/C++】運算子過載
阿新 • • 發佈:2018-12-13
C++ 中允許programmer 根據自身需要過載一系列的運算子,比如過載==
運算子就比定義 equals()
函式名了的多。但是儘量不要過載表意不明的運算子。
常用的過載運算子有 : =
, ==
, <
,>
, <<
, >>
等。
賦值運算子函式 =
定義一個賦值運算子,需要注意四點
- 返回值型別宣告為該型別的引用,在函式body結束前返回例項自身的引用
*this
. 這樣做是為了保證連續賦值,instance1 = instance2= instance3;
- 把傳入的引數型別宣告為常量引用
- 要判斷傳入的引數與當前的例項
*this
是否是同一個例項。若是,直接返回。 - 賦新值的話,在開闢新記憶體之前要釋放自身例項自身已有的記憶體。
模式就是
MyClass& MyClass::operator= (const MyClass& other) {
if(this != &other) {
//construct a temp-copy, for Exception Safety
MyClass temp(other);
// swap core data between (this, temp)
DataType* pTemp = temp.Data;
temp.Data = this.data;
this.Data = pTemp;
}
return *this;
}
code 中首先判斷是否為同一個例項,判斷為 false 後,先利用 other 複製構造一個臨時區域性變數 temp 。這樣,如果開闢新空間出問題後,this.Data
不會被改變。若正常開闢,就 swap (this, temp)
的 Data,old data 隨著 temp 在走出大括號的時候被自動析構了,new data 隨著 this
保留並返回了。Perfect code!