使用类的其他成员变量定义类的成员变量数组
Defining a class's member variable array using other member variables of that class
我是C 的新手,所以请原谅我的无知和无能。
我正在尝试创建一个名为Planet的类。每个星球都有一个宽度和高度(由于我不是一个完整的受虐狂,它们被存储为矩形(。不同的行星具有不同的宽度和高度。
因此,类需要成员变量来存储这些值。它还需要许多阵列来存储地形信息等。这些阵列的大小应由宽度和高度变量的值确定。因此每个对象都会具有不同尺寸的数组。我的问题是:如何在类中声明这些数组?
尝试使用成员变量声明数组根本不起作用:
class planet
{
public:
planet(); // constructor
~planet(); // destructor
// other public functions go here
private:
int width; // width of global map
int height; // height of global map
int terrainmap [width][height];
};
这会导致错误"非静态数据成员高度的使用无效",这显然不知道该数组应该有多大。如果我使它们成为静态变量,这也适用。
我尝试使用向量进行操作,因为它们更灵活:
vector<int> terrainmap[width][height];
但我遇到的错误完全相同。
我想我只能初始化宽度/高度可能最大值的数组或向量,但是如果此类中的某些对象具有较小的值并且不会使用整个数组,那似乎很浪费。有一个优雅的解决方案吗?
您最好使用std::vector
。为了表示2-DIM数组,您可以使用向量的向量,因此您在下面看到的声明。您甚至可以保留必要的空间,但必须在构造函数中完成。
class planet
{
public:
planet(int width, int height): width(width), height(height) {
terrainmap.reserve(width);
for(int i=0; i<width; ++i) {
terrainmap[i].reserve(height);
}
}
~planet() = default; // destructor
// other public functions go here
private:
int width; // width of global map
int height; // height of global map
std::vector< std::vector<int> > terrainmap;
};
当然,预订不是严格必要的,但是如果对象很大并且您不断将新对象推入地形图,则保留将为您节省一些内存的重新分配。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查