如何修复“无效的操作数二进制表达式”类“为”类“”错误(repl.it)

时间:2019-04-24 03:09:28

标签: c++

我目前正在编写一个简单的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 \0) 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;
}

2 个答案:

答案 0 :(得分:0)

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

class King{

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

  /* snip */
};

答案 1 :(得分:0)

在两个==对象上使用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颜色吗?在这种情况下,您可能只比较颜色(因为有一个白色国王,一个黑人国王和一个无效的国王),或者只是比较位置(因为您不能让国王占据相同的图块)而逃脱。

我刚刚演示的内容称为operator overloading,该语言可以用于大多数操作员。