使用引用左值的正确方法

Correct way to use reference lvalues

我的代码如下:

void parentheses (int n, string& str, int left, int right){

    ... irrelevant... 

}
void solve(int n){
    parentheses(n,"",0,0);
}

但是,这会给我一个错误,告诉我cannot bind non-const lvalue reference of type std::__cxx11::string& ... to an rvalue of type ‘std::__cxx11::string。在这种情况下,如果我仍然想将字符串作为引用传入,我应该如何修改我的函数?我不想让它们成为 const 因为我想修改原始字符串,我希望它们成为 & 正是因为我想编辑它们的值。

这个函数需要一个内存来改变,你没有指定是哪个。 声明一个字符串来保存你想要传递的内容以及输出到哪里。

string s = "";

并将其传递给函数

我不太确定通过引用传递 "" 的目的是什么,因为放在那里的任何值都会丢失。

无论如何,要回答您的问题,请创建一个变量并改为传递它:

void solve(int n){
    std::string tmp = "";
    parentheses(n,tmp,0,0);
}

如果你不关心tmp中存储的值,你可以忽略它。但是你需要 一些 类型的变量,即使你不关心例程最终放在那里的是什么。

函数 parentheses 需要 std::string 参数中的左值,即命名变量。但是,您在此调用中提供了一个右值(临时):

括号(n,"",0,0);

创建一个空字符串对象并将其传递给括号。您可以通过像这样更改括号的定义来避免此问题:

void parentheses (int n, const string& str, int left, int right)

此处 str 将绑定到 rvalue/temporary,但您无法在函数中更改其值。但是,如果要更改 str 的值,则必须定义一个字符串变量并将其传递给函数。

示例:

void solve(int n){
    std::string str;
    parentheses(n,str,0,0);
}

注意:不需要将 str 赋值给 "",因为字符串默认为空。

如果您想更改作为参数传递的任何字符串的字符串值(左值和右值),只需用预期的内容初始化一个变量并将其传递给您的函数。

但是如果您想区别对待左值字符串和右值字符串,只需重载您的原始函数即可。即:

void parentheses (int n, string& str, int left, int right){
    ... irrelevant... // change strings values as desired
}

void parentheses (int n, string&& str, int left, int right){
    ... irrelevant... // string as rvalue
}

您的 parentheses() 函数采用 非常量引用 std::string 对象,因此它需要一个实际的 std::string 对象引用的另一边 - 左值(可以分配给的东西)。

但是您的 solve() 函数没有传递 std::string 对象,而是传递了字符串文字。所以编译器创建了一个 temporary std::string 对象——一个右值——然后无法绑定到引用,因为临时对象不能绑定到 non-const 引用,仅对 const 引用。这就是错误消息告诉您的内容:

cannot bind non-const lvalue reference of type std::__cxx11::string& ... to an rvalue of type ‘std::__cxx11::string

solve() 需要显式创建一个实际的 std::string 对象以传递给 parentheses():

void solve(int n){
    std::string s = "";
    parentheses(n,s,0,0);
}