簡體   English   中英

C ++在枚舉中有數組值嗎?

[英]C++ Have array values in an enum?

我想知道是否有可能在枚舉中有一個數組值?

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

    } color;

這樣RED可以包含(255,0,0)值,因為這是紅色的RGB顏色代碼。

不,你不能用枚舉做到這一點。 它看起來很像你想要一個類/結構:

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];

考慮到這一點,您可以將所有這些包裝起來以使其更易於維護,但我會說這超出了這個問題的范圍。

你不能這樣做。 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};

長話短說:不,這是不可能的。

不,枚舉的定義只允許它們保存整數值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM