【发布时间】:2021-11-30 12:52:57
【问题描述】:
存在三个类 Zoo、ZooObject 和 Animal。如下所述声明 ZooObjects 的 2D 数组是否有效?如果是这样,我该如何初始化它?我熟悉动态分配二维数组,但不知道这个。
class ZooObject;
class Zoo {
public:
int rows, cols;
ZooObject ***zooArray;
Zoo(int rows, int cols) {
this->rows = rows;
this->cols = cols;
// dynamically initialize ***zooArray as a 2D array with each
//element of type Animal
// initially initialized to NULL.
// initialize each row first.
for (i = 0; i < rows; i++) {
zooArray[i] = new ZooObject *[cols];
}
// initialize each column.
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
Animal animal;
zooArray[i][j] = &animal;
}
}
}
};
class ZooObject {
public:
bool isAlive;
};
class Animal : public ZooObject {
public:
bool isHerbivore;
};
int main() { Zoo *zoo = new Zoo(3, 3); }
【问题讨论】:
-
@francesco 我熟悉这个结构。但无法弄清楚这种具体情况。
-
但是在我链接的问题的答案中,您希望实施哪些可能性?一维数组?指针数组?
-
@francesco 我已经更新了我的代码。你能检查一下这是正确的方法吗?
-
当你说你想要一个二维数组时,我认为应该只有一个分配,没有指针数组。
-
你最好使用
std::vector。
标签: c++ dynamic-memory-allocation