c++ - 枚举对象名称

标签 c++

#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/

相关文章:

c++ - 功能的优雅互斥开/关开关?

c++ - for 循环初始化中的括号

c++ - 多参数模板函数、重载和歧义错误

c++ - 如何在 gcc (g++) 中编译 C++ 代码以查看重载函数的名称修改?

c++ - 当我用 0 初始化 std::string 时发生了什么?

c++ - 关于 C++ 代码的一些解释(lambda 包装器和可变参数模板)

python - 如何从 Python 接口(interface)调试底层 C++ 库?

c++ - 在 C++/STL 中是否有与 Python range() 的紧凑等价物

c++ - 如何在 QSlider 的侧面添加图像

c++ - OpenMP 运行时间