C 賦值運算子過載函式 operator

2021-08-22 19:44:34 字數 2202 閱讀 3973

由於對c++的過載符號一直不是很理解,此處參閱一些資料給出比較詳細的解釋,方便讀者以及自己查閱。

此處有更詳細的解釋,但是其中關於 a = b = c執行順序的解釋不正確!

例1

#include

#include

using

namespace

std;

class mystr

mystr(int _id, char *_name) //constructor

mystr(const mystr& str)

mystr& operator =(const mystr& str)//賦值運算子

return *this;

}~mystr()

};int main()

結果1
constructor

********************

default

operator =

********************

copy constructor

此處可以看到執行

str2 =str1
時,呼叫了賦值運算子過載函式,可以與普通的函式呼叫一樣理解,str2為函式呼叫者,str1為函式呼叫的引數(類似於str2.***(str1))。

賦值運算子過載函式形參為引用,避免了一次物件的拷貝構造。

同樣,複製運算子過載函式函式返回值為引用,同樣避免了一次物件的拷貝構造。若返回值型別為mystr,那麼在函式返回時,將構造乙個linshi變數,並this指標指向的物件拷貝至該臨時變數。

當然,也可以不返回任何物件,設定返回值為void。但是,返回物件或者引用時可以實現連續賦值,類似於a = b = c,等價於a = (b = c);

例2(將返回型別改為mystr)

#include

#include

using

namespace

std;

class mystr

mystr(int _id, char *_name) //constructor

mystr(const mystr& str)

mystr operator =(const mystr& str)//賦值運算子

return *this;

}~mystr()

};int main()

結果2
constructor

********************

default

operator =

copy constructor

********************

copy constructor

執行

str2 =str1
時,函式返回的是物件,呼叫拷貝建構函式產生乙個臨時變數。

例3(驗證 a = b = c執行順序)

#include

#include

using

namespace

std;

class mystr

mystr(int _id, char *_name) //constructor

mystr(const mystr& str)

mystr& operator =(const mystr& str)//賦值運算子

return *this;

}~mystr()

};int main()

constructor

********************

constructor

constructor

str2 = str1

operator =

str3 = str1

operator =

********************

copy constructor

可以看到,首先構造是三個物件,name分別為str1, str2, str3。然後執行

str3 =str2 = str1
時,先是執行str2 = str1,物件str2獲取str1的name之後,str3將獲取str2新獲取的name。

C 運算子過載賦值運算子

自定義類的賦值運算子過載函式的作用與內建賦值運算子的作用類似,但是要要注意的是,它與拷貝建構函式與析構函式一樣,要注意深拷貝淺拷貝的問題,在沒有深拷貝淺拷貝的情況下,如果沒有指定預設的賦值運算子過載函式,那麼系統將會自動提供乙個賦值運算子過載函式。賦值運算子過載函式的定義與其它運算子過載函式的定義是...

賦值運算子過載函式

問題 給出如下cmystring的宣告,要求為該型別新增賦值運算子函式。class cmystring 當面試官要求應聘者定義乙個複製運算子函式時,他會關注如下幾點 是否把返回值的型別宣告為該型別的引用,並在函式結束前返回例項自身 即 this 的引用?只有返回乙個引用,才可以允許連續賦值。否則如果...

C 賦值運算子過載

c 賦值運算子過載,為什麼要返回引用?查了許多資料,基本有兩種說法 一 c c 賦值運算子的本意為 返回左值的引用 左值 賦值號左面的變數而非其值 可用以下程式段測試 int a,b 3,c 2 a b c cout 對於x y x,y均為物件時 若不返回左值的引用,將會生成臨時物件。如果不處理x ...