注:c++ 有三種傳遞方式:值傳遞,指標傳遞,引用傳遞
返回「值」和返回「引用」是不同的
函式返回值時會產生乙個臨時變數作為函式返回值的副本,而返回引用時不會產生值的副本,既然是引用,那引用誰呢?這個問題必須清楚,否則將無法理解返回引用到底是個什麼概念。以下是幾種引用情況:
當函式執行完畢,程式將釋放分配給區域性物件的儲存空間。此時,對區域性物件的引用就會指向不確定的記憶體。const string &mainip(const string &s)
同理,指標也是這樣,返回指標的時候,不能指向區域性臨時變數,否則指標將變為野指標;
四、引用返回this 的成員變數,或者 引用引數的成員變數const string &shorterstring(const string &s1,const string &s2)
delete m_string;
int len = strlen(str.m_string);
m_string = new char[len+1];
strcpy(m_string,str.m_string);
return *this;
}
原標題為:引用返回左值(上例的=賦值也是如此,即a=b=c是可以的)
原文這裡表達不清晰,因為只要是引用,都可以作為左值使用。只因為下面的例子一般用在等號左邊,當左值使用。
可以定義乙個和返回值一樣的引用型別,來接受函式的返回值,操作此引用值,和直接操作函式的引數是一樣的,引用都是使用引用傳遞;
此句進行的都是引用傳遞,故執行之後,s[0] 就變為了 a,s為「a23456」;char &get_val(string &str,string::size_type ix)
// 使用語句呼叫:
string s("123456");
cout《這種情況,和第二種是一樣的,只不過是返回了引數(引用型別)的一部分。也可以不作為左值,故修改如下:
char &ch = get_val(s,0);
ch = 『a』;
此外,可以返回引用引數的成員變數,親測有效。似乎不是區域性臨時變數,只要函式結束之後記憶體沒有被銷毀的,作為引用返回都沒問題:
五、最後轉上一段code作為總結qstring& test(student &stu)
qstring & student::getrname()
#includeusing namespace std;
string make_plural(size_t,const string&,const string&);
const string &shorterstring(const string &,const string &);
const string &mainip(const string&);
char &get_val(string &,string::size_type);
int main(void)
//返回非引用
string make_plural(size_t i,const string &word,const string &ending)
//返回引用
const string &shorterstring(const string &s1,const string &s2)
//禁止返回區域性物件的引用(我的dev c++ 沒有報錯,比較可怕)
const string &mainip(const string &s)
//引用返回左值
char &get_val(string &str,string::size_type ix)
---------------------
c 函式返回引用
1 什麼是引用?引用就是變數的別名,操作乙個變數的引用也就相當於操作變數本身,這一點跟指標很類似,但是操作引用不用像操作指標一樣,利用取位址符號,很不方便。而操作引用的話,則跟操作普通變數一樣,所以c 之中更加鼓勵使用引用。2 c 函式為什麼要使用引用?c語言之中大量利用指標作為形參或者函式返回值,...
C 函式返回引用
首先需要明白 c 函式為什麼要返回引用?答 這樣就不用返回結果的副本。因為返回副本需要做賦值拷貝函式,浪費時間。這時候,實際上,返回是結果的副本,而不是結果本身。如果要返回本身,就返回引用就ok了。例1 const string manip2 const string s 此時,返回的不是ret本身...
c 函式返回引用
一,c 函式的返回分為以下幾種情況 1 主函式main的返回值 這裡提及一點,返回0表示程式執行成功。2 返回非引用型別 函式的返回值用於初始化在跳用函式出建立的臨時物件。用函式返回值初始化臨時物件與用實參初始化形參的方法是一樣 的。如果返回型別不是引用,在呼叫函式的地方會將函式返回值複製給臨時物件...