C++對(duì)象傳遞實(shí)際應(yīng)用問題解疑
C++語言功能非常強(qiáng)大,不但能對(duì)各種程序設(shè)計(jì)提供支持,而且還具有面向?qū)ο蟮奶卣?,極大的滿足了開發(fā)人員的需求。在這里我們就先來了解一下C++對(duì)象傳遞的相關(guān)內(nèi)容,大家可以從中學(xué)到不少東西。
如果函數(shù)的返回值是一個(gè)對(duì)象,有些場(chǎng)合用C++對(duì)象傳遞中的“引用傳遞”替換“值傳遞”可以提高效率。而有些場(chǎng)合只能用“值傳遞”而不能用“引用傳遞”,否則會(huì)出錯(cuò)。
例如:
- class String
 - {⋯
 - // 賦值函數(shù)
 - String & operate=(const String &other);
 - // 相加函數(shù),如果沒有friend 修飾則只許有一個(gè)右側(cè)參數(shù)
 - friend String operate+( const String &s1, const String &s2);
 - private:
 - char *m_data;
 - }
 
String 的賦值函數(shù)operate = 的實(shí)現(xiàn)如下:
- String & String::operate=(const String &other)
 - {
 - if (this == &other)
 - return *this;
 - delete m_data;
 - m_data = new char[strlen(other.data)+1];
 - strcpy(m_data, other.data);
 - return *this; // 返回的是 *this 的引用,無需拷貝過程
 - }
 
對(duì)于賦值函數(shù),應(yīng)當(dāng)用C++對(duì)象傳遞中的“引用傳遞”的方式返回String 對(duì)象。如果用“值傳遞”的方式,雖然功能仍然正確,但由于return 語句要把 *this 拷貝到保存返回值的外部存儲(chǔ)單元之中,增加了不必要的開銷,降低了賦值函數(shù)的效率。例如:
- String a,b,c;
 - ⋯
 - a = b; // 如果用“值傳遞”,將產(chǎn)生一次 *this 拷貝
 - a = b = c; // 如果用“值傳遞”,將產(chǎn)生兩次 *this 拷貝
 - String 的相加函數(shù)operate + 的實(shí)現(xiàn)如下:
 - String operate+(const String &s1, const String &s2)
 - {
 - String temp;
 - delete temp.data; // temp.data 是僅含‘\0’的字符串
 - temp.data = new char[strlen(s1.data) + strlen(s2.data) +1];
 - strcpy(temp.data, s1.data);
 - strcat(temp.data, s2.data);
 - return temp;
 - }
 
對(duì)于相加函數(shù),應(yīng)當(dāng)用“值傳遞”的方式返回String 對(duì)象。如果改用“引用傳遞”,那么函數(shù)返回值是一個(gè)指向局部對(duì)象temp 的“引用”。由于temp 在函數(shù)結(jié)束時(shí)被自動(dòng)銷毀,將導(dǎo)致返回的“引用”無效。例如:
- c = a + b;
 
此時(shí) a + b 并不返回期望值,c 什么也得不到,流下了隱患。
以上就是對(duì)C++對(duì)象傳遞的相關(guān)介紹。
【編輯推薦】















 
 
 
 
 
 
 