C++ 关于C++; #包括 #包括 使用名称空间std; 字符串和funRef(字符串和s){ 字符串t=s; 返回t; } int main(){ string s1=“我是一根绳子!”; 字符串&s2=funRef(s1); s2=“你的绳子是我的”; cout

C++ 关于C++; #包括 #包括 使用名称空间std; 字符串和funRef(字符串和s){ 字符串t=s; 返回t; } int main(){ string s1=“我是一根绳子!”; 字符串&s2=funRef(s1); s2=“你的绳子是我的”; cout,c++,C++,您的大多数代码都是无关的 这归结为简单的未定义行为,因为在这里您将返回对局部变量的引用: #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

您的大多数代码都是无关的

这归结为简单的未定义行为,因为在这里您将返回对局部变量的引用:

#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;
}
funRef
的调用一结束,字符串
t
就会消失,但您稍后会尝试使用对
t
的引用


您不能这样做。

它引用了一个已销毁的对象,
string t=s;
t
funref
不在范围内时被销毁。
string& funRef(string& s)
{
   string t = s;
   return t;
}