gpt4 book ai didi

c++ - 在 if 语句中比较枚举类型时出错

转载 作者:行者123 更新时间:2023-11-28 06:46:02 24 4
gpt4 key购买 nike

每当我尝试使用 findPieceAt 函数在数组中给我一个位置时,我都会收到错误消息。在下面的代码中。

if (findPieceAt(newRow, newCol) != -1)
{
if (chessPieces[findPieceAt(newRow, newCol)].getColor == turn) //line with error
{
cout << "invalid attack on same color" << endl;
return false;
}
else
{
if (chessPieces[findPieceAt(oldRow, oldCol)].captureMove(newRow, newCol) == true);
{
chessPieces[findPieceAt(newRow, newCol)].isCaptured;
cout << "capture of " << chessPieces[findPieceAt(newRow, newCol)].getFullName << " is successful" << endl;
return true;
}
}
}

findPieceAt函数如下所示。

int Chess::findPieceAt(int row, int col)
{
for (int index = 0; index < NUM_CHESS_PIECES; index++)
{

if (chessPieces[index].isAt(row, col) == true)
{
return index;
}
else
{
return -1;
}
}
}

getColor 函数如下所示。

Color ChessPiece::getColor()
{
return color;
}

转弯定义如下

void Chess::gameLoop(istream & input)
{

Color turn = Black; // Black will start the game

棋子数组

private:
static const int NUM_ROWS = 8, NUM_COLS = 8;
static const int NUM_CHESS_PIECES = 32;
ChessPiece chessPieces[NUM_CHESS_PIECES];
};

使用的枚举类型

enum ChessPieceType { Pawn, Rook, Knight, Bishop, Queen, King };
enum Color { White, Black };

最佳答案

您缺少括号,因为 getColor 是一个函数调用:

    if (chessPieces[findPieceAt(newRow, newCol)].getColor() == turn )

此外,您可以缓存 findPieceAt(newRow, newCol) 的值,而不是在您的代码中重复调用它。

此外,由于您没有发布有错误的整个函数,因此您需要确保在所有退出点返回一个 bool。如果 findPieceAt(newRow, newCol) 返回 -1,您发布的代码可能不会返回任何内容。不从具有返回类型的函数返回值是未定义的行为。

关于c++ - 在 if 语句中比较枚举类型时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24972560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com