毕竟它们在构造函数初始化后就不能修改了?
我是不是错过了什么?
真实问题:
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 标准中)编译它会出现以下错误:
array size in new-expression must be constant
,‘this’ is not a constant expression
。
为什么?
我是否理解正确,您想要创建二维数组(类成员“结构”)? 如果是这样,代码应该是这样的:
bool** structure;
…
Maze(const int& size_x, const 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