C++ C++;类中的字符数组声明

C++ C++;类中的字符数组声明,c++,arrays,oop,char,C++,Arrays,Oop,Char,我正在创建一个游戏,我想将屏幕数据保存在数据类型为char的1D数组中。屏幕数据必须是类中的全局变量。数组的大小将在初始化后确定。在构造函数中会声明一些常量值,用于计算数组的确切大小 class Screen { public: Screen(uint16_t width, uint16_t height); private: const uint16_t WIDTH; const uint16_t HEIGHT; char field[WIDTH * HEIG

我正在创建一个游戏,我想将屏幕数据保存在数据类型为char的1D数组中。屏幕数据必须是类中的全局变量。数组的大小将在初始化后确定。在构造函数中会声明一些常量值,用于计算数组的确切大小

class Screen
{
public:
    Screen(uint16_t width, uint16_t height);
private:
    const uint16_t WIDTH;
    const uint16_t HEIGHT;

    char field[WIDTH * HEIGHT];
};

Screen::Screen(uint16_t width, uint16_t height)
   : WIDTH(width),
    HEIGHT(height)
{
 
}

这显示了一个错误,因为宽度和高度是类的非静态成员。如果我在每个维度声明(宽度、高度)中的const之前添加关键字static,它会显示其他错误,表示它不能用作常量值。那么,如何解决这个错误呢?

数组大小必须是编译时常量。使用向量代替

#include <vector>

class Screen
{
public:
    Screen(uint16_t width, uint16_t height);
private:
    uint16_t WIDTH;
    uint16_t HEIGHT;

    std::vector<char> field;
};

Screen::Screen(uint16_t width, uint16_t height)
   : WIDTH(width), HEIGHT(height), field(width*height)
{ 
}
#包括
类屏幕
{
公众:
屏幕(uint16的宽度,uint16的高度);
私人:
uint16_t宽度;
uint16_t高度;
std::向量场;
};
屏幕::屏幕(uint16的宽度,uint16的高度)
:宽度(宽度)、高度(高度)、字段(宽度*高度)
{ 
}