[英]invalid initialization of non-const reference of type ‘std::string& from an rvalue of type ‘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();
}
首先,調用main()
是非法的,所以return main();
是未定義的行為。 如果您想多次運行main()
的代碼,請使用do..while
循環。
當string[]
數組在傳遞給spell()
時衰減為指向第一個元素的string*
指針時,編譯器抱怨的右值出現了。 您對a
的聲明是一個非常量左值引用,它不能綁定到右值,因此會出現編譯器錯誤。
spell()
不會修改a
自身以指向其他地方,它只是訪問數組中a
指向的string
對象,因此不需要通過引用傳遞a
,通過值傳遞它就可以了:
void spell(int n, string* a)
或者,通過const
引用傳遞它也可以,因為 const 左值引用可以綁定到右值:
void spell(int n, string* const &a)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.