#include <iostream>
using namespace std;
enum color {
black=1, blue, green, cyan, red, purple, yellow, white
} colors;
int main(){
color mycolor;
mycolor = blue;
cout << mycolor;
return 0;
}
对象名称颜色有什么用途吗?我是否可以使用枚举打印出任何这些颜色的名称,或者我只能打印出每种颜色对应的常量?
最佳答案
Is there any usage for object name colors?
是:如果您想要 color
类型的全局变量,您可以在 enum color
声明之后立即定义它.
could I be able to print out the name of any of these color by using Enumerations or I only can print out the constant number which each of color corresponding to?
不,您将无法打印 enum
的名称给定枚举值的成员,除非您在自己的代码中构建一个系统,通过该系统您可以将常量“解码”回字符串表示形式。一种常见的方法是创建字符串文字的并行数组:
#define TO_STR(X) #X
const char* color_names = {"none", TO_STR(black), TO_STR(blue), TO_STR(green), ...};
如您所见,无法将枚举转换为字符串不适用于编译时已知的枚举常量:您可以使用 a preprocessor trick to stringify them .
将枚举值映射到字符串的另一种常见方法是使用 std::map<color,std::string>
。不过,它与并行数组类似,您需要手动初始化它。它对于“标志”枚举(即不使用顺序值的枚举)效果更好。
关于c++ - 枚举对象名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16577323/