如何使用抽象类的Polymorphy 2D数组进行创建

how can I create with Polymorphy 2D-Array of abstract class?

本文关键字:数组 创建 2D Polymorphy 何使用 抽象类      更新时间:2023-10-16

我想要一个包含抽象类Piece的2D指针数组。因此,我在一个名为Board的类中创建了一个指向Piece的2D数组的指针,该类具有Board的私有字段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;
};

不能对数组使用多态性。

数组包含大小相同的连续元素。但是多态元素可能具有不同的大小,因此编译器将无法生成正确索引元素的代码。

您最终可以考虑一个指向多态元素的指针数组:

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.