0

我是 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;
4

2 回答 2

2

一个函数如

string& returnRefrence(){}

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

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

string& foo(string& s) {
  // do something with s
  return s;
}
于 2012-09-09T14:16:32.327 回答
0

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

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

于 2012-09-09T18:35:30.487 回答