日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

何时可以返回引用

發布時間:2024/9/5 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 何时可以返回引用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

EFfective C++和More Effective C++中有講解。

“條款23: 必須返回一個對象時不要試圖返回一個引用”

“條款31: 千萬不要返回局部對象的引用,也不要返回函數內部用new初始化的指針的引用”

?

為什么要返回引用呢——為了實現鏈式操作。

返回一個對象不行嗎?為什么有時要返回引用呢?主要是為了實現鏈式操作。

看一個例子就明白了:

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
?MyString& MyString::operator =(const?MyString &other) {
??? /*if (this != &other) {
??????? size = strlen(other.data);
??????? char *temp = new char[size + 1];
??????? strcpy(temp, other.data);
??????? delete []data;
??????? data = temp;
??? }
??? return *this;*/
?
??? if (this != &other) {
??????? MyString strTmp(other);
?
??????? char *pTmp = strTmp.data;
??????? strTmp.data = data;
??????? data = pTmp;
??? }
?
??? return *this;
}

當返回引用時,我們可以實現鏈式操作如 (s1 = s2) = s3.如果返回的是對象,就不能這么操作了!

MyString s1;

MyString s2;

MyString s3 = “hello”;

(s1 = s2) = s3;

如果返回的是引用,則s1被賦值為"hello";如果是局部對象,則s1沒被賦值!

?

?

?

注意和+ – * /運算符重載相區別(返回局部對象):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
?String String::operator +(const String &str)???
{
??? String newstring;
??? if (!str.m_string)
??? {
??????? newstring = *this;
??? }
??? else?if (!m_string)
??? {
??????? newstring = str;
??? }
??? else
??? {
??????? int len = strlen(m_string)+strlen(str.m_string);
??????? newstring.m_string = new?char[len+1];
??????? strcpy(newstring.m_string,m_string);
??????? strcat(newstring.m_string,str.m_string);
??? }
??? return newstring;
}

何時返回引用呢

有兩種情況可以返回引用。一種是普通函數,返回傳入參數的引用;另一種是類方法函數,返回this對象的引用。

只要記住這兩種情況,其他情況如果可以也是沒什么意義的。

?

一、返回傳入參數的引用。

如運算符<<的友元重載形式:

1
2
3
4
5
?ostream& operator<< (ostream &out, MyString &s)
{
??? out << s.data;
??? return out;
}

?

二、返回this對象的引用。

即上面string的 = 運算符重載。

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
?MyString& MyString::operator =(const?MyString &other) {
??? /*if (this != &other) {
??????? size = strlen(other.data);
??????? char *temp = new char[size + 1];
??????? strcpy(temp, other.data);
??????? delete []data;
??????? data = temp;
??? }
??? return *this;*/
?
??? if (this != &other) {
??????? MyString strTmp(other);
?
??????? char *pTmp = strTmp.data;
??????? strTmp.data = data;
??????? data = pTmp;
??? }
?
??? return *this;
}

?

?

最終總結:返回引用的情況有兩種,一種是普通函數,返回傳入參數的引用;另一種是類方法函數,返回this對象的引用。

不可以返回局部對象的引用,也不要返回函數內部用new初始化的指針的引用(可能會造成內存泄露).

轉載于:https://www.cnblogs.com/helloweworld/p/3208585.html

總結

以上是生活随笔為你收集整理的何时可以返回引用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。