如何使用抽象类的Polymorphy 2D数组进行创建
how can I create with Polymorphy 2D-Array of abstract class?
我想要一个包含抽象类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.
相关文章:
- 在c++中为double类型的数组创建一个unique_ptr
- 如何从预定义的数组创建某些元素数组
- 基于数组的列表 - 动态数组创建时出错
- 从 UTF-8 字节数组创建字符串?
- 是否可以在并行区域中为共享 2D 数组创建选定元素的线程本地副本?(共享,私有,障碍:OPenMP)
- C++ 从名称数组创建对象
- 从数组创建 Mat 时,'cv::Mat' 和 'int' 类型不兼容
- 从 std::数组创建十六进制代表
- 在 C++ 结构内声明的数组 A[1] 创建多个实例
- 为多维数组创建内存空间
- 如何使用任何类型的数组创建模板类并为其设置值?
- 从字符串数组创建一个字符数组
- 是否可以在不为该数组创建变量的情况下将数组作为参数传递到函数中?
- 使用类定义数组创建C++类
- 使用具有唯一随机数的结构数组创建多个对象
- 谷歌测试:无法从字符数组创建字符串
- 从 1D 数组创建 2D 数组
- 无法通过一个单向链表数组创建邻接列表
- 如何使用数组创建标准::函数
- 在C++中,返回从本地字符数组创建的字符串是否会导致内存泄漏或未定义的行为