在 C++ 中通过引用和值传递字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28390902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing strings by reference and value in C++
提问by Peter
I want to declare a string, initialize it by passing it by reference, and then pass it by value to the 'outputfile' function.
我想声明一个字符串,通过引用传递它来初始化它,然后将它按值传递给 'outputfile' 函数。
The code below works, but I don't know why. In main I would expect to pass the string 'filename' like
下面的代码有效,但我不知道为什么。在主要我希望通过字符串“文件名”像
startup(&filename)
But that gives an error, and the code below doesn't. Why? Also, is there a better way to do this without using a return value?
但这会产生错误,而下面的代码则不会。为什么?另外,有没有更好的方法来做到这一点而不使用返回值?
#include <iostream>
#include <string>
using namespace std;
void startup(std::string&);
void outputfile(std::string);
int main()
{
std::string filename;
startup(filename);
outputfile(filename);
}
void startup(std::string& name)
{
cin >> name;
}
void outputfile(std::string name)
{
cout << name;
}
回答by emlai
Your code works as expected.
您的代码按预期工作。
&filename
returns the memory address of (aka a pointer to) filename
, but startup(std::string& name)
wants a reference, not a pointer.
&filename
返回 (aka 一个指向) 的内存地址filename
,但startup(std::string& name)
想要一个引用,而不是一个指针。
References in C++ are simply passed with the normal "pass-by-value" syntax:
C++ 中的引用只是通过普通的“按值传递”语法传递:
startup(filename)
takes filename
by reference.
startup(filename)
需要filename
通过参考。
If you modified the startup
function to take a pointer to an std::string
instead:
如果您修改startup
函数以获取指向 an 的指针std::string
:
void startup(std::string* name)
void startup(std::string* name)
then you would pass it using the address-of operator:
那么您将使用 address-of 运算符传递它:
startup(&filename)
startup(&filename)
As a side note, you should also make the outputfile
function take its parameter by reference, because there's no need to copy the string. And since you're not modifying the parameter, you should take it as a const
reference:
作为旁注,您还应该让outputfile
函数通过引用获取其参数,因为不需要复制字符串。并且由于您没有修改参数,因此您应该将其作为const
参考:
void outputfile(const std::string& name)
For more info, here are the rules of thumb for C++regarding how to pass function parameters.