0
#include <iostream>
#include <string>
using namespace std;
string& funRef (string& s) {
string t = s;
return t;
}
int main() {
string s1 = "I'm a string!";
string& s2 = funRef(s1);
s2 = "YOUR STRING IS MINE";
cout << s1 << endl;
cout << s2 << endl;
}
參考爲什麼它打印出來:關於C++
我是一個字符串!
\ 367 \ 277_ \ 377 \ 367 \ 277_ \ 377M
我想S2被分配以 「您的字符串是我的」。
s2發生了什麼?
它引用了一個被銷燬的對象,'string t = s;''t'在'funref'不在範圍內時被銷燬。 – George