从 'std::string* {aka 类型的右值初始化 'std::string*& {aka std::basic_string<char>*&}' 类型的非常量引用无效
Invalid initialization of non-const reference of type 'std::string*& {aka std::basic_string<char>*&}' from an rvalue of type 'std::string* {aka
我正在尝试解决这个我必须拼写数字的问题。
当我尝试通过引用调用我的字符串数组 a
时,出现此错误。但是如果我按值调用它,我不会出错。
我不知道右值从哪里来,因为我的字符串元素应该被视为左值。
#include <iostream>
#include <string>
using namespace std;
void spell(int n,string* &a){
if(n==0)
return;
spell(n/10,a);
cout<<a[n%10];
}
int main(){
int n;
cin>>n;
string a[10]{"zero ","one ","two ","three ","four ","five ","six ","seven ","eight ","nine "};
spell(n,a);
if(n<0)
return 0;
return main();
}
首先,calling main()
is illegal,所以 return main();
是 未定义的行为 。如果您想多次使用 运行 main()
的代码,请使用 do..while
循环。
当 string[]
数组 decays 传递给 spell()
时,编译器抱怨的右值出现在指向第一个元素的 string*
指针中。您对 a
的声明是一个非常量左值引用,它不能绑定到右值,因此会出现编译器错误。
spell()
不会修改 a
本身指向其他地方,它只是访问 a
指向的数组中的 string
对象,所以有不需要通过引用传递 a
,通过值传递就可以了:
void spell(int n, string* a)
或者,通过 const
引用传递它也可以,因为 const 左值引用可以绑定到右值:
void spell(int n, string* const &a)
我正在尝试解决这个我必须拼写数字的问题。
当我尝试通过引用调用我的字符串数组 a
时,出现此错误。但是如果我按值调用它,我不会出错。
我不知道右值从哪里来,因为我的字符串元素应该被视为左值。
#include <iostream>
#include <string>
using namespace std;
void spell(int n,string* &a){
if(n==0)
return;
spell(n/10,a);
cout<<a[n%10];
}
int main(){
int n;
cin>>n;
string a[10]{"zero ","one ","two ","three ","four ","five ","six ","seven ","eight ","nine "};
spell(n,a);
if(n<0)
return 0;
return main();
}
首先,calling main()
is illegal,所以 return main();
是 未定义的行为 。如果您想多次使用 运行 main()
的代码,请使用 do..while
循环。
当 string[]
数组 decays 传递给 spell()
时,编译器抱怨的右值出现在指向第一个元素的 string*
指针中。您对 a
的声明是一个非常量左值引用,它不能绑定到右值,因此会出现编译器错误。
spell()
不会修改 a
本身指向其他地方,它只是访问 a
指向的数组中的 string
对象,所以有不需要通过引用传递 a
,通过值传递就可以了:
void spell(int n, string* a)
或者,通过 const
引用传递它也可以,因为 const 左值引用可以绑定到右值:
void spell(int n, string* const &a)