2015-01-14 38 views
1

雖然有解決方案很容易convert an enum to a string,我想使用enum class的額外安全好處。有沒有簡單的方法將enum class轉換爲字符串?有沒有一種簡單的方法將枚舉類轉換爲字符串(C++)?

(給出的解決方案不起作用,因爲枚舉類不能索引數組)。

+3

您可以使用'std :: unordered_map'來代替。 –

+0

_「提供的解決方案不起作用,因爲枚舉類不能索引數組」_您可以詳細說明這個問題,或者給出一個示例嗎?我不明白enum class應該是不同的。 –

+2

@πάνταῥεῖ你不能隱式地將一個'enum類'轉換爲它的底層類型,這就是它們的一個重點。 – sjdowling

回答

2

你不能隱式地轉換爲基礎類型,但你可以明確地做到這一點。

enum class colours : int { red, green, blue }; 
const char *colour_names[] = { "red", "green", "blue" }; 
colours mycolour = colours::red; 
cout << "the colour is" << colour_names[static_cast<int>(mycolour)]; 

如果這太冗長了,這取決於你。

1

您是否使用VS C++。下面的代碼示例MSDN

using namespace System; 
public ref class EnumSample 
{ 
public: 
    enum class Colors 
    { 
     Red = 1, 
     Blue = 2 
    }; 

    static void main() 
    { 
     Enum^myColors = Colors::Red; 
     Console::WriteLine("The value of this instance is '{0}'", myColors); 
    } 

}; 

int main() 
{ 
    EnumSample::main(); 
} 

/* 
Output. 
The value of this instance is 'Red'. 
*/ 
+0

{Red = 0x100,Blue = 0x10000,Green = 0x1000000 }? –

+1

明智的SSCE,你可以向我解釋'^'語法,因爲我不熟悉它? –

+1

@ MikeH-R這隻適用於C++ cli。 –

相關問題