按引用和值传递字符串C++

Passing strings by reference and value in C++

本文关键字:字符串 C++ 值传 引用      更新时间:2023-10-16

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

下面的代码有效,但我不知道为什么。 总的来说,我希望传递字符串"文件名",例如

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

您的代码按预期工作。

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

C++中的引用只是使用正常的"按值传递"语法传递:

startup(filename)通过引用filename


如果将 startup 函数修改为改为采用指向std::string的指针:

void startup(std::string* name)

然后,您将使用地址运算符传递它:

startup(&filename)


作为旁注,您还应该使 outputfile 函数通过引用获取其参数,因为无需复制字符串。由于您没有修改参数,因此应将其视为const参考:

void outputfile(const std::string& name)

有关详细信息,下面是有关如何传递函数参数C++的经验法则。