我想要一个包含名为Piece的抽象类的2D指针数组。所以我在一个名为Board的类中创建了一个指向一个2D数组的指针,该类具有私有字段-Piece ** _board。
我尝试使用矢量或用类封装电路板字段,但显然出现了问题。
class Piece
{
public:
Piece(bool, string);
Piece(){};
bool isChass(bool, Board*);
virtual int move(int x_src, int y_src, int x_dst, int y_dst, Board* board)=0;
virtual ~Piece();
bool get_isWhite();
string get_type();
Piece(Piece & other);
Piece& operator= (const Piece & other);
bool inRange(int, int);
protected:
bool _isWhite;
string _type;
};
class Board
{
public:
Board();
Board(const Board& other);
~Board();
Board& operator=(const Board &other);
Piece& getPiece(int i, int j){ return _board[i][j]; }
void game();
void deletePiece(int x, int y) { delete &_board[x][y]; }
void allocateBlankPiece(int x, int y) { _board[x][y] = *new Blank(); }
private:
Piece** _board;
bool _isWhiteTurn;
friend class Piece;
friend class Rock;
friend class Bishop;
friend class Queen;
friend class Knight;
friend class King;
friend class Pawn;
};
答案 0 :(得分:2)
您不能对数组使用多态性。
数组包含相同大小的连续元素。但是多态元素的大小可能不同,因此编译器无法生成代码来正确索引元素。
你最终可以考虑一个指向多态元素的指针数组:
Piece*** _board; // store pointers to polyorphic elements
但使用矢量会更实际,更安全:
vector<vector<Piece*>> _board; // Vector of vector of poitners to polymorphic elements
您还可以考虑更安全的智能指针:
vector<vector<shared_ptr<Piece>>> _board; // assuming that several boards or cells could share the same Piece.