C 過載 使用引用返回函式值

2021-09-09 07:28:54 字數 1169 閱讀 3591

參考:

#include

#include

using

namespace std;

class

string

/*copy construct*/

string

(const string& other)

~string()

};string::

string

(const

char

* s)

//建構函式定義

string string::

operator=(

const string &other)

//運算子過載

intmain()

執行結果:

當運算子過載返回的是物件時,會在賦值運算過程的返回途中呼叫兩次拷貝建構函式和析構函式(因為return的是個新的物件)。

如果採用 string& operator+(const string& str) 這樣就不會有多餘的呼叫(因為這裡直接return乙個已經存在的物件的引用)。

#include

#include

using

namespace std;

class

string

string

(const string &p)

~string()

string operator=(

const string &);

//宣告賦值運算子過載函式 屬於成員運算子過載函式

//string &operator屬於使用引用返回函式值,返回函式的值型別為 string

//const string & 屬於使用常引用作為函式引數 學習筆記30 };

string string::

operator=(

const string &s)

intmain()

執行結果:

c 函式未返回函式值

test0 include include using namespace std int add int a,int b int main int argc,char ar int main int argc,char ar int main int argc,char ar int main i...

c 返回函式區域性物件的引用

在上面的 中,最後能夠輸出正確的值,然而在函式getnode 中,str是乙個區域性的物件,記憶體空間在棧上,當函式退出時,str的記憶體空間被 這是在高階語言的層面上講的。但是為什麼最後的結果是正確的?原因就是node newnode getnode 這句呼叫的是預設的拷貝建構函式,如果是自己重新...

c 返回函式區域性物件的引用

函式千萬不要返回區域性物件的引用或指標 區域性變數在函式裡面,當函式執行結束後將釋放區域性變數,如果返回引用或批針這個時候引用或指標指向所指向的記憶體空間已經釋放。指標和引用將是垂懸指標。很危險!但是如果返回的 區域性變數 是堆中的記憶體值就可以返回了 c 函式為什麼要使用引用?c語言之中大量利用指...