c++ - C++中的枚举和匿名枚举

标签 c++

1) 下面的代码显示了 枚举元素 wednesday 的索引。我怎样才能让它打印值而不是索引。

int main()
{
    enum day{sunday,monday,tuesday,wednesday,thursday,friday,saturday};
    day d=wednesday;
    cout<<d;
    return 0;
}

2) 在什么情况下我更喜欢匿名枚举而不是枚举

最佳答案

1).您的代码打印枚举的值,而不是索引。在您的具体示例中,索引与值相同(默认情况下,枚举的第一个值获得数值 0,其余值获得连续递增的值。

检查:

int main()
{
    enum day{sunday = 5,monday,tuesday,wednesday,thursday,friday,saturday};
    day d=wednesday;
    cout<<d; // will print 8 (as in 5 + 1 + 1 + 1)
    return 0;
}

如果“打印值”是指打印“星期三”,您应该这样做:

enum day{sunday,monday,tuesday,wednesday,thursday,friday,saturday};

std::ostream& operator << (std::ostream& out, const day d)
{
    static const char *as_strings[] = {"sunday", "monday",
        "tuesday", "wednesday", "thursday", "friday", "saturday"
    };
    return out << as_strings[static_cast<int>(d)]; // this only works 
                 // for enum values starting from 0 and being consecutive
                 // otherwise you should use a switch(d) and 
                 // print each value separately
}

int main()
{
    day d=wednesday;
    cout<<d; // will print wednesday
    return 0;
}

编辑:

2) In what situation will I prefer anonymous enum over enum

当您不需要将其作为参数传递但需要为常量数值分配有意义的名称时,您更喜欢匿名枚举:

my_object record_to_myobject(record& r)
{
    enum {id, value1, value2}; // indexes within record
    int result_id = r[id]; // much more meaningful than r[0]
    int result_value1 = r[value1];
    int result_value2 = r[value2];
    return my_object{result_id, result_value1, result_value2};
}

在这里使用匿名枚举很好,因为在将值作为参数传递的地方,您需要一个 int,而不是枚举类型。如果你需要一个枚举类型,那么你必须给它一个名字。否则,你不会。

关于c++ - C++中的枚举和匿名枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17831882/

相关文章:

c++ - 检查二维数组中的相邻索引

c++ - 为什么我的归并排序最后会放一个随机的 4?

c++ - 在定点类型上实现模数

c++ - 为什么 GCC 不编译这段代码?

c++ - 输入 64 位数字

c++ - 从 unary_function 继承的谓词仿函数,它不是一个接受 1 个参数的函数

c++ - SFML 纹理持有者已删除,但仍在范围内

C++ 宏代码 - 将(任意大小的)显式整数转换为指针类型

c++ - 在 3ds max 中识别平面对象

c++ - 从对象数组中选择一个随机对象