2012-09-09 73 views
0

即時通訊新的指針和參考C++,所以我想知道如果有人可以告訴我一個如何編寫一個函數,返回一個字符串refrence,也許正在使用的函數的一個例子。例如,如果我想編寫一個函數像...函數返回一個字符串參考C++

//returns a refrence to a string 
string& returnRefrence(){ 


    string hello = "Hello there"; 
    string * helloRefrence = &hello; 

    return *helloRefrence; 
} 

//and if i wanted to use to that function to see the value of helloRefrence would i do something like this? 

string hello = returnRefrence(); 
cout << hello << endl; 

回答

2

的函數,例如

string& returnRefrence(){} 

只會有意義的背景下哪裏是訪問一個string一種生活超越它自己的範圍。例如,這可能是一個具有string數據成員的類的成員函數,或者可以訪問某個全局​​字符串對象的函數。在函數主體中創建的字符串在退出該作用域時被銷燬,因此返回對其的引用會導致懸掛引用。

另一種選擇哪裏是可以使的感覺是,如果函數tkaes引用一個字符串,並返回到非常字符串的引用:

string& foo(string& s) { 
    // do something with s 
    return s; 
} 
+0

好了,如果我是寫返回一個字符串refrence功能像上面那樣的字符串。如果找不到字符串,我可以返回我在函數內部創建的變量嗎? – user1489599

+0

@ user1489599您不應該返回對函數內部創建的任何內容的引用,正如在「dangling reference」中說明的那樣。 – juanchopanza

+0

哦,我現在明白了,所以它不會在函數終止後存在。好的,謝謝。 – user1489599

0

你也可以將變量聲明爲靜態:

std::string &MyFunction() 
{ 
    static std::string hello = "Hello there"; 
    return hello; 
} 

但是,請注意,完全相同的字符串對象將作爲每次調用的引用返回。

例如,

std::string &Call1 = MyFunction(); 
Call1 += "123"; 

std::string Call2 = MyFunction(); //Call2 = "Hello there123", NOT "hello there" 

的CALL2對象是CALL1引用相同的字符串,所以它返回其修改後的值