我目前正在编写一个简单的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;
}
您需要重载该类的==运算符。
class King{
private:
bool operator==(const King& k) const
{
return m_x == k.m_x && m_y == k.m_y;
}
/* snip */
};
在两个==
对象上使用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,它可以用于语言中的大多数操作符。