类和 2D 动态数组

Classes and 2D Dynamic Array

本文关键字:数组 动态 2D 类和      更新时间:2023-10-16

我在让 2D 类数组填充其他类对象时遇到了麻烦。

基类:

class Base {
protected:
    int x, y;
    int moves;
    char name;
    bool occupied;
public:
    Base();
    friend ostream& operator<<(ostream& os, const Base& test);
};

派生类:

class Derived : public Base {
private:
    const int x = 10;
    const int y = 60;
    Base **array;
public:
    Derived();
    void printBoard();
};

派生类的构造函数:

创建 2D 动态数组

Derived::Derived() {
    array = new Base*[x];
    for (int i = 0; i < x; i++) 
         array[i] = new Base[y];
}

派生类 2:

class Derived2: public Base{
public:
    Derived2(int x, int y);
};

如何让 2D 数组接受并随后正确显示该数组中的对象?

每当我尝试

Derived[x][y] = new Derived2(x,y);

它似乎不起作用,我真的认为我被困了一段时间:(

我不明白DerivedBase之间的关系:

  1. Derived是一个Base
  2. Derived 有一个数组 Base

你不能做Derived[x][y],这要求Derived有一个用户定义的operator[],它将返回另一个数组(如果可以使其static(。如果要访问array,则需要Derived实例并为array提供"getter"函数。

你需要有一个 2D 指针数组来做多态性:Base ***array; ,像这样分配它:

array = new Base**[x];
for (int i = 0; i < x; i++) 
     array[i] = new Base*[y];
// this gives you 2D array of uninitialized pointers

而且你忘了在Base的析构函数中删除这个数组。这就是你的做法。资源管理应该是您实施的第一件事,并确保它是正确的。之后的逻辑是。

这是"getter"函数(public(:

Base ***Derived::getArray() const
{
    return array; // array is private, you access it with this function
}

并在代码中使用它:

int x = 1, y = 2;
Derived d; // create an instance - this calls Derived's constructor, allocates array
d.getArray()[x][y] = new Derived2(x, y);

我建议使用std::vector(或std::array,因为您有常量维度(而不是动态分配的数组。