C ++重载==运算符示例

时间:2017-04-27 10:54:40

标签: operator-overloading c++14

制作国际象棋游戏,我不能重载==运算符(认为这是问题,如果我在数组中正确添加元素,则为。)

enum squerState{EMPTY, ROOK, KNIGHT, BISHOP, QUEEN, KING, PAWN};

class Board
{
public:
Board();
~Board();

friend bool operator==(const Board& lhs, const Board& rhs);

squerState stanjePolja;
squerColor bojaPolja;
pieceColor bojaFigurice;

Board* board[8][8];
};

//。CCP

Board* piece;
for(int x= 0; x < 8; x++)
{
     for(int y=0; y < 8; y++)
    {
    piece->stanjePolja = squerState::ROOK;
    piece->bojaPolja = squerColor::WHITE;
    piece->bojaFigurice = pieceColor::BLACK_PIECE;

    board[y][x] = piece;
    }
}

// overload ==

bool operator==(const Board& lhs, const Board& rhs)
{
    return lhs.stanjePolja == rhs.stanjePolja;

}

//绘制测试板

void Board::drawBoard()
{
    for (auto y = 0; y < 8; y++)
    {
        for (auto x = 0; x < 8; x++)
        {
            if (board[y][x] == squerState::ROOK)
            {
                std::cout << 'O';
            }
            else
                std::cout << 'X';
        }
        std::cout << std::endl;
    }
}

问题是当我尝试使用ROOK来绘制测试板时。

if (board[y][x] == squerState::ROOK)

谢谢!

1 个答案:

答案 0 :(得分:0)

在第

if (board[y][x] == squerState::ROOK)

看起来左侧的表达式类型为Board*,但右侧的表达式类型为enum squerState。您没有为这些类型定义等于运算符,也无法通过其他方式进行比较。

您可能希望Board类包含SquareState个实例的数组。

enum Piece { None, Pawn, ... };
enum Color { Black, White };

struct SquareState
{
     Piece piece_;
     Color color_;
};

struct Board
{
    void drawBoard() const;
    SquareState board_[8][8];
};

void Board::drawBoard() const
{
     for( int i = 0; i < 8; ++i )
     {
          for( int j = 0; j < 8; ++j )
          {
               switch( board_[ i ][ j ].piece_ )
               {
                    case Piece::None:
                        std::cout << " ";
                        break;
                    case Piece::Pawn:
                        std::cout << "P";
                        break;
                    // ...
               }
          }
          std::cout << std::endl;
     }
}

我希望这会有所帮助。