如何使用抽象的多态二维数组 class 创建?
how can I create with Polymorphy 2D-Array of abstract class?
我想要一个二维指针数组,其中包含名为 Piece 的抽象 classes。所以我在一个名为 Board 的 class 中创建了一个指向 Piece 的二维数组的指针,它具有 board -Piece** _board 的私有字段。
我尝试使用向量或用 class 包装 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;
};
不能对数组使用多态性。
数组包含相同大小的连续元素。但是多态元素可能具有不同的大小,因此编译器将无法生成代码来正确索引元素。
你最终可以考虑指向多态元素的指针数组:
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.
我想要一个二维指针数组,其中包含名为 Piece 的抽象 classes。所以我在一个名为 Board 的 class 中创建了一个指向 Piece 的二维数组的指针,它具有 board -Piece** _board 的私有字段。
我尝试使用向量或用 class 包装 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;
};
不能对数组使用多态性。
数组包含相同大小的连续元素。但是多态元素可能具有不同的大小,因此编译器将无法生成代码来正确索引元素。
你最终可以考虑指向多态元素的指针数组:
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.