[英]C++ vector of vector of abstract class
对于一个简单的国际象棋游戏,我想创建(棋子)矢量的2D矢量。 所以我的课看起来像
class board {
private:
int width, height; //dimensions
vector<vector<piece> > pieces2D;
public:
board(int w=8, int h=8)
{
width = w; height = h;
vector<vector<piece>> pieces2D(w, vector<piece>(h, 0));
}
其中piece是一个抽象类,所以我不能使用数组。 但是我无法在构造器中创建默认大小为8x8的pieces2D。 什么东西少了? 我还赞赏其他解决方案来存储64(抽象)件。
您无法实例化抽象类-因此无法构造包含抽象类型的向量。
这里的解决方案是存储指针vector<vector<std::unique_ptr<piece>>>
: vector<vector<std::unique_ptr<piece>>>
首先,您不能将抽象类用作std :: array,std :: vector或任何其他STL容器类的模板。 如果要使用多态性,请使用std :: unique_ptr或std :: shared_ptr存储指向对象的指针。
可以对pieces2D成员进行初始化
class board {
private:
int width, height; //dimensions
vector<vector<piece> > pieces2D;
public:
board(int w=8, int h=8)
: pieces2D(w, vector<piece>(h, 0))
{
width = w; height = h;
}
};
但是,如果不将其替换为std :: shared_ptr,它将无法正常工作。 恕我直言,也最好对这些碎片使用平面(一维)阵列,因为那样一来,您只需要管理一个堆块。 您可以使用()运算符(或简单的成员函数)按行和列访问片段:
class Board
{
private:
int width, height;
std::vector<std::shared_ptr<Piece>> pieces;
public:
Board(int width_, int height_)
: width(width_),
height(height_),
pieces(width_ * height_)
{}
std::shared_ptr<Piece>& operator()(int row, int col)
{
return pieces[row*width+col];
}
};
并使用它:
Board board(8, 8);
board(1, 2) = std::make_shared<PawnPiece>();
类属性piece2D的初始化不正确。
您试图做的是初始化class属性,但是实际上要做的是初始化构造函数本地的对象,该对象名为pieces2D,当程序超出构造函数范围时将被销毁。
另外,您无法实例化抽象对象的向量,因为无法从抽象类实例化任何对象。 但是您可以实例化一个指向抽象对象的指针的向量,并为其分配指向从基本抽象类派生的具体对象的指针。
您寻找的可能是pieces2D的初始化列表。
喜欢 :
class board {
private:
int width, height; //dimensions
vector<vector<piece*> > pieces2D;
public:
board(int w=8, int h=8): pieces2D(w, vector<piece*>(h, 0))
{
width = w; height = h;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.