毕竟它们在构造函数初始化后无法修改,我是否遗漏了一些东西?
真实问题:
class Maze {
private:
struct Coordinate {
int x, y;
Coordinate(const int &x, const int &y): x(x), y(y) {}
};
const Coordinate size;
bool* structure;
public:
Maze(const int &size_x, const int &size_y):
size(size_x, size_y) {
structure = new bool[(size.x * 2 - 1)][(size.y * 2 - 1)];
}
};
使用 G++(在 C++17 标准中)编译此代码会出现此错误:
new-表达式中的数组大小必须是常量
和
‘this’不是常量表达式
为什么?
我是否理解正确,您想要创建二维数组(类成员“结构”)? 如果是这样,代码应该是这样的:
bool** structure;
…
Maze(int size_x, int size_y) :
size(size_x, size_y) {
size_t rows_count = size.x * 2 - 1;
size_t cols_count = size.y * 2 - 1;
structure = new bool*[rows_count];
for (int i = 0; i < rows_count; ++i)
structure[i] = new bool[cols_count];
}
不要忘记编写析构函数来释放内存。 你最好使用 std::vector