av激情亚洲男人的天堂国语,日韩欧美精品一中文字幕,无码av一区二区三区无码,国产又色又爽又刺激的a片,国产又色又爽又刺激的a片

C++對(duì)象傳遞實(shí)際應(yīng)用問題解疑

C++語言功能非常強(qiáng)大,不但能對(duì)各種程序設(shè)計(jì)提供支持,而且還具有面向?qū)ο蟮奶卣鳎瑯O大的滿足了開發(fā)人員的需求。在這里我們就先來了解一下C++對(duì)象傳遞的相關(guān)內(nèi)容,大家可以從中學(xué)到不少東西。

如果函數(shù)的返回值是一個(gè)對(duì)象,有些場(chǎng)合用C++對(duì)象傳遞中的“引用傳遞”替換“值傳遞”可以提高效率。而有些場(chǎng)合只能用“值傳遞”而不能用“引用傳遞”,否則會(huì)出錯(cuò)。

例如:

 
 
 
  1. class String
  2. {?
  3. // 賦值函數(shù)
  4. String & operate=(const String &other);
  5. // 相加函數(shù),如果沒有friend 修飾則只許有一個(gè)右側(cè)參數(shù)
  6. friend String operate+( const String &s1, const String &s2);
  7. private:
  8. char *m_data;
  9. }

String 的賦值函數(shù)operate = 的實(shí)現(xiàn)如下:

 
 
 
  1. String & String::operate=(const String &other)
  2. {
  3. if (this == &other)
  4. return *this;
  5. delete m_data;
  6. m_data = new char[strlen(other.data)+1];
  7. strcpy(m_data, other.data);
  8. return *this; // 返回的是 *this 的引用,無需拷貝過程
  9. }

對(duì)于賦值函數(shù),應(yīng)當(dāng)用C++對(duì)象傳遞中的“引用傳遞”的方式返回String 對(duì)象。如果用“值傳遞”的方式,雖然功能仍然正確,但由于return 語句要把 *this 拷貝到保存返回值的外部存儲(chǔ)單元之中,增加了不必要的開銷,降低了賦值函數(shù)的效率。例如:

 
 
 
  1. String a,b,c;
  2. ?
  3. a = b; // 如果用“值傳遞”,將產(chǎn)生一次 *this 拷貝
  4. a = b = c; // 如果用“值傳遞”,將產(chǎn)生兩次 *this 拷貝
  5. String 的相加函數(shù)operate + 的實(shí)現(xiàn)如下:
  6. String operate+(const String &s1, const String &s2)
  7. {
  8. String temp;
  9. delete temp.data; // temp.data 是僅含‘\0’的字符串
  10. temp.data = new char[strlen(s1.data) + strlen(s2.data) +1];
  11. strcpy(temp.data, s1.data);
  12. strcat(temp.data, s2.data);
  13. return temp;
  14. }

對(duì)于相加函數(shù),應(yīng)當(dāng)用“值傳遞”的方式返回String 對(duì)象。如果改用“引用傳遞”,那么函數(shù)返回值是一個(gè)指向局部對(duì)象temp 的“引用”。由于temp 在函數(shù)結(jié)束時(shí)被自動(dòng)銷毀,將導(dǎo)致返回的“引用”無效。例如:

 
 
 
  1. c = a + b;

此時(shí) a + b 并不返回期望值,c 什么也得不到,流下了隱患。

以上就是對(duì)C++對(duì)象傳遞的相關(guān)介紹。


分享標(biāo)題:C++對(duì)象傳遞實(shí)際應(yīng)用問題解疑
分享地址:http://uogjgqi.cn/article/dhohjod.html
掃二維碼與項(xiàng)目經(jīng)理溝通

我們?cè)谖⑿派?4小時(shí)期待你的聲音

解答本文疑問/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流