2016-06-09 42 views
2

我想知道是否有可能在一個枚舉中的數組值?實施例C++在枚舉中有數組值?

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

    } color; 

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

+1

枚舉是不是真的意味着包含值。你可以有一個'static const int enumValues [numColors] [3]'包含對應於枚舉的顏色。你仍然可以做'enum RGB {RED = 0xff000,BLUE = 0x00ff00,...}'。 – coyotte508

+0

是的我知道在最壞的情況下,我只是用它來代替。謝謝您的幫助 –

回答

1

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

0

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

3

不,你不能這樣做與枚舉。

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

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