即時通訊新的指針和參考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;
好了,如果我是寫返回一個字符串refrence功能像上面那樣的字符串。如果找不到字符串,我可以返回我在函數內部創建的變量嗎? – user1489599
@ user1489599您不應該返回對函數內部創建的任何內容的引用,正如在「dangling reference」中說明的那樣。 – juanchopanza
哦,我現在明白了,所以它不會在函數終止後存在。好的,謝謝。 – user1489599