我是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& returnRefrence(){}


仅在可以访问超出其自身范围的string的上下文中才有意义。例如,这可以是具有string数据成员的类的成员函数,或者是可以访问某些全局字符串对象的函数。在函数主体中创建的字符串在退出该范围时将被销毁,因此返回对其的引用将导致悬空引用。

另一个可行的选择是,该函数是否按引用来处理字符串,并返回对该字符串的引用:

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

关于c++ - 返回字符串引用的函数C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12339812/

10-11 22:35
查看更多