我正在尝试用C++做一个国际象棋模拟。我已经创建了一个类Pieces,我想在堆上创建一个由所有块组成的二维数组。这是我的代码:国王、王后和其他人都是从碎片中派生出来的。
king = new King();
queen = new Queen();
knight = new Knight();
bishop = new Bishop();
rook = new Rook();
pawn = new Pawn();
empty = new Pieces();
Pieces* startup[64] = {rook, knight, bishop, king, queen, bishop, knight, rook,
pawn, pawn, pawn, pawn, pawn, pawn, pawn, pawn,
empty, empty, empty, empty, empty, empty, empty, empty,
empty, empty, empty, empty, empty, empty, empty, empty,
empty, empty, empty, empty, empty, empty, empty, empty,
empty, empty, empty, empty, empty, empty, empty, empty,
pawn, pawn, pawn, pawn, pawn, pawn, pawn, pawn,
rook, knight, bishop, king, queen, bishop, knight, rook};
Pieces* board = new Pieces[8][8];
int k = 0;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
board[i][j] = startup[k];
k++;
}
}但这给了我以下错误:
ChessBoard.cpp: In constructor ‘ChessBoard::ChessBoard()’:
ChessBoard.cpp:25: error: cannot convert ‘Pieces (*)[8]’ to ‘Pieces*’ in initialization
ChessBoard.cpp:29: error: no match for ‘operator[]’ in ‘board[i][j]’如何在堆上成功分配一个二维数组?另外,创建一个指向块的指针数组还是创建一个块对象数组更好呢?
发布于 2014-01-15 22:15:15
为什么你需要所有的动态分配?简单地使用64个元素的枚举数组,并在顶部添加一些伪造的2D索引。
下面是一个例子:
#include <array>
#include <iostream>
enum class piece_t
{
EMPTY = 0, PAWN, ROOK, BISHOP, KNIGHT, QUEEN, KING
};
static const size_t WIDTH = 8, HEIGHT = 8;
struct board_t : std::array<piece_t, WIDTH*HEIGHT>
{
board_t()
{
for (size_t y = 0; y < HEIGHT; y++)
for (size_t x = 0; x < WIDTH; x++)
operator()(x,y) = piece_t::EMPTY;
}
piece_t& operator()(size_t x, size_t y)
{
return operator[](x + y*WIDTH);
}
const piece_t& operator()(size_t x, size_t y) const
{
return operator[](x + y*WIDTH);
}
};
std::ostream& operator<<(std::ostream& os, const piece_t& piece)
{
switch (piece) {
case piece_t::KING: return (os << 'K');
case piece_t::QUEEN: return (os << 'Q');
case piece_t::KNIGHT: return (os << 'N');
case piece_t::BISHOP: return (os << 'B');
case piece_t::ROOK: return (os << 'R');
case piece_t::PAWN: return (os << 'P');
case piece_t::EMPTY: return (os << ' ');
default: return (os << '?');
}
}
std::ostream& operator<<(std::ostream& os, const board_t& board)
{
os << '+' << std::string(WIDTH, '-') << '+' << '\n';
for (size_t y = 0; y < HEIGHT; y++) {
os << '|';
for (size_t x = 0; x < WIDTH; x++)
os << board(x, y);
os << '|' << '\n';
}
os << '+' << std::string(WIDTH, '-') << '+' << '\n';
return os;
}
int main()
{
board_t b;
b(3, 5) = piece_t::KING;
b(6, 4) = piece_t::KNIGHT;
std::cout << b << std::endl;
// etc.
}Live demo
简单得多,也更安全。:-)
发布于 2014-01-15 22:13:28
您只需要两个简单的更改。委员会的声明应为:
Pieces (*board)[8] = new Pieces[8][8];换句话说,board是指向8元素数组(数组)的指针。那么作业应该是:
board[i][j] = *startup[k];请注意,棋盘是一个二维的棋子数组,而不是一个指针数组,这可能是您真正想要的。
发布于 2014-01-15 21:22:32
创建电路板阵列,如下所示
Pieces** board=new Pieces*[8];
for (int i=0; i<8; i++)
{
board[i] = new Pieces[8];
}https://stackoverflow.com/questions/21138427
复制相似问题