【问题标题】:How to allocate memory to a 2D array of objects in c++? [duplicate]如何在 C++ 中为二维对象数组分配内存? [复制]
【发布时间】: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


【解决方案1】:

正如已经提到的,这是一篇不错的帖子,对问题的一般答案进行了详细解释。 How do I declare a 2d array in C++ using new?

在您的情况下,如果您想将其存储为二维数组。您应该首先分配所有行,其中每一行是一个ZooObject**,即ZooObject 的指针数组。 之后,对于每一行,您应该分配ZooObject* 的数组(列)。你会有这样的东西:

    Zoo(int rows, int cols) {
        this->rows = rows;
        this->cols = cols;

        zooArray = new ZooObject**[rows];
        for (int i = 0; i < rows; ++i) {
            zooArray[i] = new ZooObject*[cols];
            for (int j = 0; j < cols; ++j) {
                zooArray[i][j] = nullptr;
            }
        }
    }

但是,考虑使用一维数组,您仍然可以通过二维访问它,通过相应的方法,将rowId, colId对转换为一维。

另外,别忘了deletenew

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • 我什至可以有更多类继承自基类 Animal,如 Carnivorous、Herbivorous 等。因此,Animal 将是一个抽象类。我相信这个初始化zooArray[i][j] = new Animal; 会抛出错误。
  • @taurus05,你是对的。我们可以在单元格中存储任何派生类对象,因为单元格的类型为ZooObject*new Animal 就是一个例子。最好在那儿分配nullptr,然后再分配我们想要的正确对象。
  • @BonnyCash 谢谢!
  • 当你说你想要一个二维数组时,我认为应该只有一个分配,没有指针数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-01
  • 2012-02-05
相关资源
最近更新 更多