我一直在 StackOverlow 周围寻找答案,但我没有找到答案,所以我希望这不是这里任何帖子的重复。
所以,我有下一个问题。
假设我有接下来的 2 个类:Rectangle(它是从另一个类构建的,但它目前不关心我们)和Grid。他们跟随构造函数:
(矩形私有 topLeft 和 bottomRight 的点构造函数):
Point::Point(int x, int y) {this->x = x; this->y = y;}
(矩形构造函数和类)
class Rectangle
{
public:
Rectangle(int l, int u, int w, int h, int color);
//int getColor() const;
//void setColor(int color);
//bool contains(const Point &p) const;
//void print() const;
private:
const Point topLeft, bottomRight;
int color;
};
Rectangle::Rectangle(int l, int u, int w, int h, int color) :
topLeft(l, u),
bottomRight(l + w, u + h)
{ this->color = color; }
(网格构造函数和类)(假设我不想在网格中初始化 Rectangle 的值,只是将它们分配到内存中)
class Grid
{
public:
Grid(int tileW, int tileH, int width, int height, int color);
//~Grid();
//Rectangle& getRectAt(const Point &p);
//void print() const;
private:
int count;
Rectangle **recs;
};
Grid::Grid(int tileW, int tileH, int width, int height, int color)
{
int index, index_c=0;
recs = new Rectangle *[width];
for (int index = 0; index < width; index++)
{
recs[index] = new Rectangle[index];
}
}
所以,正如你所理解的,我在 Grid 构造函数中遇到了以下错误
(错误 1 错误 C2512:'矩形':没有合适的默认构造函数可用。)
但我只是不明白为什么它不起作用,我被建议分配Recs 双指针作为一维数组(长度为 Width*Height 的数组)但是如果 Recs 是 4 维数组呢?你怎么能正确地把它展平,然后在 4 维数组周围进行索引,而不用为计算数组中每个单元格的索引而头疼。
另一件事,我们知道如果它是 int** 而不是 recs** 它将完美地工作
int **foo;
int height,width;
foo = new int* (height);
for (int index = 0; index<height; ++index)
foo[index] = new int[width];
所以我只是一直想念在 C++ 中做 n 维数组的方式。