簡體   English   中英

從類型&#39;std :: basic_string的右值對類型&#39;std :: string&的非常量引用進行了無效的初始化<char>

[英]invalid initialization of non-const reference of type ‘std::string& from an rvalue of type ‘std::basic_string<char>

bool hasWord(int y, int x, string &word) {
    if(!inRange(y, x)) return false; 
    if(board[y][x] != word[0])  return false; 
    if(word.size() == 1) return true; 
    for(int direction = 0; direction < 8; direction++) {
        int nextX = x + dx[direction];
        int nextY = y + dy[direction];
        if(hasWord(nextY, nextX, word.substr(1)))  // <--- This
            return true;
    }
return false; }

錯誤:從類型'std :: basic_string'的右值初始化非'std :: string&{aka std :: basic_string&}'類型的非常量引用if(hasWord(nextY,nextX,word.substr(1)) )

為什么我錯了?

錯誤消息說明了一切: 從類型為std::basic_string的右值對類型為std::string {aka std::basic_string }的非常量引用進行了無效的初始化

即,對非常量的引用不能綁定到臨時對象(即r值)。 該臨時對象由word.substr(1)表達式創建。

在聲明中:

bool hasWord(int y, int x, string &word)

將其設置為string const& word ,因為您不需要可修改的word

錯誤的原因是在此調用中

if(hasWord(nextY, nextX, word.substr(1))) 
                         ^^^^^^^^^^^^^^ 

會創建一個類型為std :: string的臨時對象,並且您試圖將一個非恆定引用與該臨時對象綁定。

如果函數中的字符串未更改,則只需聲明該函數,例如

bool hasWord(int y, int x, const string &word) {
                           ^^^^^

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM