【问题标题】:Passing strings by reference and value in C++在 C++ 中通过引用和值传递字符串
【发布时间】:2015-04-08 01:53:28
【问题描述】:

我想声明一个字符串,通过引用传递它来初始化它,然后通过值传递给'outputfile'函数。

下面的代码有效,但我不知道为什么。在 main 中,我希望传递字符串 'filename' 之类的

startup(&filename)

但这会产生错误,而下面的代码不会。为什么?另外,有没有更好的方法可以在不使用返回值的情况下做到这一点?

#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;
}

【问题讨论】:

  • &amp;filename 创建一个指针。指针和引用不兼容。
  • 为什么不想使用返回值?
  • 代码“有效”,因为它完全按照您的描述进行。在你的开场白中,做得很好。关于&amp;filename 的错误,它不应该编译,因为引用不是指针。见this question and answers。关于它们的异同。

标签: c++ string pass-by-reference pass-by-value


【解决方案1】:

您的代码按预期工作。

&amp;filename 返回filename 的内存地址(也称为指针),但startup(std::string&amp; name) 需要引用,而不是指针。

C++ 中的引用只是使用普通的“按值传递”语法传递:

startup(filename) 引用 filename


如果您修改了startup 函数以获取指向std::string 的指针:

void startup(std::string* name)

然后您将使用地址操作符传递它:

startup(&amp;filename)


附带说明,您还应该让outputfile 函数通过引用获取其参数,因为不需要复制字符串。而且由于您没有修改参数,因此您应该将其作为const 参考:

void outputfile(const std::string& name)

有关如何传递函数参数的更多信息,here are the rules of thumb for C++

【讨论】:

    猜你喜欢
    • 2010-12-24
    • 2014-08-11
    • 2017-07-25
    • 2016-07-05
    • 2016-04-09
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多