如何修复类"Invalid operands to binary expression "类" to "类" "错误 (repl.it)

how to fix "Invalid operands to binary expression "class" to "class"" error (repl.it)

本文关键字:to repl it 错误 expression Invalid operands binary 何修复      更新时间:2023-10-16

我目前正在编写一个简单的 2 人国际象棋游戏。我目前的点是根据类的成员变量查找用户尝试移动的对象(类(。我创建了一个函数来基于变量返回类的实例,但是当我尝试将返回的值(==(与类的对象进行比较时,出现"二进制表达式的操作数无效"错误。

// this is the important class
class King{
private:
const char m_color;
int m_x;
int m_y;
public:
void setStartBlack(){
    m_color = 'B';
    m_x = 4;
    m_y = 0;
    board[m_y][m_x] = 'K';
}
void setStartWhite(){
    m_color = 'W';
    m_x = 4;
    m_y = 7;
    board[m_y][m_x] = 'K';
}
int getMX(){
    return m_x;
}
int getMY(){
    return m_y;
}
};
// this is the function I made to return the class instance
King checkPieceK(int x, int y){ // x and y is the column and row
if (blackKing.getMX() == x && blackKing.getMY() == y){
    return blackKing; // I should note here that blackKing is an 
// object of the king class and so is whiteKing
}
else if (whiteKing.getMX() == x && whiteKing.getMY() == y){
    return whiteKing;
}
else{
    return failureCondK; // this is what should be returned if the 
// piece doesn't exist at the location checked
}
}
// and here's what's happening at main()
while (GAMEOVER == false){
std::cout << " enter the row, column and type of the piece you 
want to move(e.g. "G1P" means "G1," Pawn): ";
row = getchar();
col = getchar();
typ = getchar();
getchar(); // catches newline (n or ) char
row = toupper(row);
int newRow = detYval(row);
typ = toupper(typ);
if (typ == 'K'){
    if (checkPieceK(col - 1, newRow) == failureCondK){ // this is 
// the statement is where the error occurs
    }
}
GAMEOVER = true;
}
编译器

不知道在两个King对象上使用 == 运算符时该怎么做。您必须定义操作。这涉及到编写一个具有特殊名称(operator==(的函数来比较King对象。

class King {
public:
  bool operator==(const King &rhs) const {
    return m_color == rhs.m_color && m_x == rhs.m_x && m_y == rhs.m_y;
  }
  // whenever you define operator==, you should also define operator!=
  bool operator!=(const King &rhs) const {
    return !(*this == rhs);
  }
  // ...
};

如果你想比较国王,你可以做king.operator==(otherKing)king == otherKing.如果您愿意,还可以将operator==定义为非成员函数(在类外部(。

class King {
  // ...
};
bool operator==(const King &lhs, const King &rhs) {
  return lhs.m_color == rhs.m_color && lhs.m_x == rhs.m_x && lhs.m_y == rhs.m_y;
}
bool operator!=(const King &lhs, const King &rhs) {
  return !(lhs == rhs);
}

现在您可以将国王与operator==(king, otherKing)king == otherKing进行比较.

您可能需要对operator==的定义进行一些思考。我们真的需要比较颜色,x和y吗?在这种情况下,您可能只能比较颜色(因为有一个白色国王,一个黑人国王和一个无效的国王(或只是比较位置(因为你不能让国王占据同一个图块(。

我刚刚演示的内容称为运算符重载,它可以用于该语言中的大多数运算符。

您需要重载该类的 == 运算符。

class King{
private:
  bool operator==(const King& k) const
  {
    return m_x == k.m_x && m_y == k.m_y;
  }
  /* snip */
};