【问题标题】:C++ char array declaration in ClassClass 中的 C++ char 数组声明
【发布时间】:2020-12-13 16:35:34
【问题描述】:

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

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)
{
 
}

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

【问题讨论】:

    标签: c++ arrays oop char


    【解决方案1】:

    数组大小必须是编译时常量。请改用向量。

    #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)
    { 
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      相关资源
      最近更新 更多