尝试创建具有未知大小的模板类的2D数组(C ++)

时间:2014-11-29 19:13:19

标签: c++ arrays pointers initialization

我有一个包含成员变量的类:

T** board

这应该代表游戏板上的单元格,其中每个单元格都是T类型,这是一个抽象类。电路板的大小是在运行时确定的(因此指针而不是数组声明)。

在同一个类的构造函数中,我尝试初始化构成该板的数组:

template<class T, class J, const int X, const int Y>
Gameboard<T,J,X,Y>::Gameboard() {
    board = new T[X];
    for (int i = 0; i < X; i++) {
        board[i] = new T[Y];
    }
}

但是,我收到以下错误:

In file included from main.cpp:17:
./Gameboard.h:40:17: error: allocating an object of abstract class type 'Tile'
    board = new T[X];
In file included from main.cpp:17:
./Gameboard.h:42:24: error: allocating an object of abstract class type 'Tile'
        board[i] = new T[Y];

我应该如何正确创建2D数组呢?

2 个答案:

答案 0 :(得分:1)

一般来说,我采取的方法是制作2D std::vector。如果你真的想确保在编译时固定长度,那么你可以使用std::array

#include <array>
template<class T, class J, const int X, const int Y>
class Gameboard{

std::array< std::array<T, Y>, X> board;
}

这应默认初始化所有元素。如果这不符合您的要求,那么您可以根据需要轻松编写自己的初始化。

答案 1 :(得分:0)

您需要为X指向-T,

的数组分配第一个内存
board = new T* [X];

而不是现在的board = new T[X];

或者,正如评论/答案中所述,只需使用std::vectorstd::array