【问题标题】:C++ Have array values in an enum?C++ 枚举中有数组值吗?
【发布时间】:2016-06-09 15:03:09
【问题描述】:

我想知道枚举中是否可以有一个数组值?示例

    enum RGB {
      RED[3],
      BLUE[3]

    } color;

这样RED 可以包含(255,0,0) 的值,因为这是红色的RGB 颜色代码。

【问题讨论】:

  • 枚举并不真正意味着包含值。你可以有一个 static const int enumValues[numColors][3] 包含对应于枚举的颜色。你仍然可以做enum RGB { RED = 0xff000, BLUE=0x00ff00, ...}
  • 是的,我知道在最坏的情况下我只会使用它。感谢您的帮助

标签: c++ arrays enums


【解决方案1】:

你不能那样做。 enum 中的标记只能保存整数值。

一个可能的解决方案:

struct Color {uint8_t r; uint8_t g; uint8_t b;}; 

Color const RED = {255, 0, 0};
Color const GREEN = {0, 255, 0};
Color const BLUE = {0, 0, 255};

【讨论】:

    【解决方案2】:

    不,你不能用枚举来做到这一点。看起来很像你想要一个类/结构:

    class Color {
    public:
        int red;
        int green;
        int blue;
    
        Color(int r, int g, int b) : red(r), green(g), blue(b) { }
    };
    

    一旦定义了该类,就可以将其放入容器(例如数组、向量)并查找它们。例如,您可以使用枚举来引用数组中的元素。

    enum PresetColor {
        PRESET_COLOR_RED,
        PRESET_COLOR_GREEN,
        PRESET_COLOR_BLUE,
    };
    
    ...
    Color presetColors[] = { Color(255, 0, 0), Color(0, 255, 0), Color(0, 0, 255) };
    
    Color favouriteColor = presetColors[PRESET_COLOR_GREEN];
    

    考虑到这一点,您可以将所有这些都包装起来以便更易于维护,但我想说这超出了这个问题的范围。

    【讨论】:

      【解决方案3】:

      长话短说:不,这是不可能的。

      【讨论】:

        【解决方案4】:

        不,枚举的定义只允许它们保存整数值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多