类和 2D 动态数组
Classes and 2D Dynamic Array
我在让 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);
它似乎不起作用,我真的认为我被困了一段时间:(
我不明白Derived
和Base
之间的关系:
-
Derived
是一个Base
-
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
,因为您有常量维度(而不是动态分配的数组。
相关文章:
- std::向量与传递值的动态数组
- 将数组动态分配到具有指针参数的函数中
- 我可以以某种方式使我的矢量/数组动态更改装置数量吗?
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 为什么C 没有方便的方式来为多维数组动态分配内存
- 如何制作具有动态大小的数组?动态数组的一般用法(可能还有指针)
- c++中的数组动态内存分配
- 多维数组动态分配的内存图
- 如何在 c++ 中使用 2-D 固定数组为 4-D 数组动态分配内存
- C++ 我在数组/动态内存方面遇到了一些问题
- C++ 中从数组动态强制转换
- C++中高维数组动态内存分配的正确方法.
- 从 C++ 结构中包含的指针数组动态分配和访问内存
- 对象数组动态内存分配
- 为二维数组动态分配内存时出错
- 如何将2d数组动态分配给结构
- 为结构数组c++动态分配内存
- 将数组动态添加到多维数组
- 类中的类数组-动态数组(c++)有问题
- 分配对象数组动态冻结