简体   繁体   English

怎样用Polymorphy 2D-Array创建抽象类?

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

I want to have a 2D array of pointers that contains abstract classes called Piece. 我想要一个2D指针数组,其中包含称为Piece的抽象类。 So I made a pointer to a 2D array of Piece in a class called Board that have private field of board -Piece** _board. 因此,我在名为Board的类中指向了Piece的2D数组的指针,该数组具有board -Piece ** _board的私有字段。

I tried to use vector or wrap the board field with class but apperently something went wrong.. 我试图使用vector或用类包装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;
};

You can't use polymorphism for arrays. 您不能对数组使用多态。

An array contains contiguous elements of the same size. 数组包含相同大小的连续元素。 But polymorphic elements could be of different size, so that the compiler would not be able to generate code to properly indexing the elements. 但是多态元素的大小可能不同,因此编译器将无法生成代码以对元素进行正确索引。

You can eventually consider an array of pointers to polymorphic elements: 您最终可以考虑一个指向多态元素的指针数组:

Piece*** _board;  // store pointers to polyorphic elements 

But it would be more practical and safer to use vectors: 但是使用向量会更实用,更安全:

vector<vector<Piece*>> _board;  // Vector of vector of poitners to polymorphic elements

You could also consider even safer smart pointers: 您还可以考虑使用更安全的智能指针:

vector<vector<shared_ptr<Piece>>> _board;    // assuming that several boards or cells could share the same Piece.  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM