有没有一种简单的方法可以将枚举 class 转换为字符串 (c++)?
Is there a simple way to convert an enum class to a string (c++)?
虽然有解决方案可以轻松解决 convert an enum to a string,但我想要使用 enum class
的额外安全优势。有没有一种简单的方法可以将 enum class
转换为字符串?
(给出的解决方案不起作用,因为枚举 class 无法索引数组)。
您不能隐式转换为基础类型,但可以显式转换。
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)];
是否太冗长,由您决定。
您使用的是 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'.
*/
虽然有解决方案可以轻松解决 convert an enum to a string,但我想要使用 enum class
的额外安全优势。有没有一种简单的方法可以将 enum class
转换为字符串?
(给出的解决方案不起作用,因为枚举 class 无法索引数组)。
您不能隐式转换为基础类型,但可以显式转换。
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)];
是否太冗长,由您决定。
您使用的是 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'.
*/