【问题标题】:Getting the error "no match for operator==" working with a 2d array使用 2d 数组时出现错误“不匹配 operator==”
【发布时间】:2013-03-29 19:59:46
【问题描述】:

我在尝试使用“==”和“!=”与字符串数组和字符进行比较时遇到此错误。这是否意味着我需要做一些运算符重载?如果是这样,谁能指出我如何做到这一点(或其他方法)的正确方向,因为我对运算符重载还不太熟悉。

bool legalMove(string list[][7], int row_start, 
    int column_start, int row_end,int column_end)
{
if(list[row_start][column_start] == 'S' && list[row_end][column_end] != ' ')
    {
        if((row_end == row_start + 1 && column_start == column_end) || 
            (row_start == row_end && (column_end == column_start + 1 
                || column_end == column_start  - 1)))
            {
                return true;
            }
            else
            {
                return false;
            }


    }
    else
    {
        return false;
    }
 }

【问题讨论】:

  • 这可能是因为您试图将stringchar 进行比较
  • 一个字符串只是一个字符数组,但不是吗?所以 list[x][y] 在任何给定时间都等于一个字符。还是不正确?
  • 字符串是一个字符数组,不同于一个字符。您的假设很接近,但实际上list[x][y][z] 是一个角色。因此,您可以通过两种方式更改代码。把你的单引号改成双引号,或者检查list[row_start][column_start][0] == 'S' && list[row_end][column_end][0] != ' '
  • 好的,我明白了。回想起来,这是一个愚蠢的问题,哈哈。感谢您的帮助。
  • 没问题。重要的是你学到了一些有用的东西。

标签: arrays overloading operator-keyword


【解决方案1】:

您正在使用''std::stringchar 进行比较。试试吧

if(list[row_start][column_start] == "S" && list[row_end][column_end] != " "){ }

如果您使用的是std::string,那是标准类型,您将无法重载operator==。有关std::string 的参考,请参阅here

【讨论】:

  • 哇哦...所以您可以使用赋值运算符将字符设置到字符串中,但不能使用比较运算符检查字符?
  • 例如,在另一个函数中,我需要将数组的某些部分设置为空格,所以我这样做了:list[0][0] = '';列表[0][1] = ' ';
猜你喜欢
  • 1970-01-01
  • 2011-10-06
  • 2012-08-04
  • 2014-05-16
  • 2011-12-10
  • 2013-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多