返回字符串引用c++; 我对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; //返回对字符串的引用 string&returnreference(){ string hello=“你好”; 字符串*helloRefrence=&hello; 返回*helloRefrence; } //如果我想使用这个函数来查看helloRefrence的值,我会这样做吗? 字符串hello=returnreference(); cout

返回字符串引用c++; 我对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; //返回对字符串的引用 string&returnreference(){ string hello=“你好”; 字符串*helloRefrence=&hello; 返回*helloRefrence; } //如果我想使用这个函数来查看helloRefrence的值,我会这样做吗? 字符串hello=returnreference(); cout,c++,C++,A函数,如 string& returnRefrence(){} 只有在is可以访问超出其自身范围的字符串的上下文中才有意义。例如,这可能是一个类的成员函数,该类具有字符串数据成员,或者是一个可以访问某个全局字符串对象的函数。在函数体中创建的字符串在退出该作用域时被销毁,因此返回对它的引用将导致挂起引用 另一个有意义的选项是,如果函数通过引用调用字符串,并返回对该字符串的引用: string& foo(string& s) { // do something wit

A函数,如

string& returnRefrence(){}
只有在is可以访问超出其自身范围的
字符串的上下文中才有意义。例如,这可能是一个类的成员函数,该类具有
字符串
数据成员,或者是一个可以访问某个全局字符串对象的函数。在函数体中创建的字符串在退出该作用域时被销毁,因此返回对它的引用将导致挂起引用

另一个有意义的选项是,如果函数通过引用调用字符串,并返回对该字符串的引用:

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

您还可以将变量声明为静态:

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中引用的字符串相同,因此它返回了其修改后的值

Ok,那么如果我编写一个函数,像上面那样返回字符串s的字符串引用,该怎么办。如果找不到字符串,我可以让它返回我在函数内部创建的变量吗?@user1489599您不应该返回对函数内部创建的任何内容的引用,正如“悬挂引用”一句中所解释的。哦,我现在理解了,所以函数终止后它就不存在了。好的,谢谢。