首页 文章

从'std :: basic_string <char>类型的右值开始,无效初始化'std :: string&类型的非const引用

提问于
浏览
2
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; }

错误:如果(hasWord(nextY,nextX,word.substr(1))从'std :: basic_string'类型的右值开始,无效初始化'std :: string&{aka std :: basic_string&}'类型的非const引用)

为什么我错了?

2 回答

  • 1

    错误消息说明了这一点:从 std::basic_string 类型的右值开始,无效初始化 std::string {aka std::basic_string }类型的非const引用 .

    即对非const的引用不能绑定到临时对象(也称为r值) . 该临时对象由 word.substr(1) 表达式创建 .

    在声明中:

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

    设为 string const& word ,因为您不需要可修改的 word .

  • 3

    错误的原因是在此调用中

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

    创建了一个std :: string类型的临时对象,并且您尝试将非常量引用与临时对象绑定 .

    如果函数中没有更改字符串,那么只需声明函数即可

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

相关问题