gpt4 book ai didi

c++ - 枚举对象名称

转载 作者:搜寻专家 更新时间:2023-10-31 01:09:50 31 4
gpt4 key购买 nike

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

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com