函数,该函数返回一个字符串引用c++
Function that returns an string refrence 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& returnRefrence(){}
只有在is可以访问超出其自身范围的string
的情况下才有意义。例如,这可以是具有string
数据成员的类的成员函数,也可以是可以访问某个全局字符串对象的函数。在函数体中创建的字符串在退出该作用域时会被销毁,因此返回对它的引用会导致悬空引用。
另一个有意义的选项是,如果函数通过引用tkaes一个字符串,并返回对该字符串的引用:
string& foo(string& s) {
// do something with s
return s;
}
您也可以将变量声明为static:
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中引用的字符串相同,因此它返回了修改后的值
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何仅为一个函数添加延迟
- 构造函数正在调用一个使用当前类类型的函数
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 如何创建函数管道,以便函数一个接一个地运行?
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 在c++中的复制构造函数/一个声明语句中的初始化的延续中使用chain方法
- C :基类调用自己的虚拟函数 - 一个反图案
- 如何在这个交换函数(一个单独的链表)中找到错误
- 两个相同的函数(一个使用模板模式,另一个不使用)
- 你怎么能一次给一个函数一个参数呢
- 为什么要做两个函数?(一个是非const,另一个是const)
- 当代码在其他地方使用时,如何保证函数一个接一个地被调用