此枚举是否有效,如果有效,为什么

Is this enumeration valid, and if so, why?

本文关键字:有效 为什么 如果 枚举 是否      更新时间:2023-10-16
enum color = {blue, black=3, yellow=3};

2种颜色的值为3,有效吗?我认为枚举必须具有不同的值。

它是有效的,因为它是允许的。可能不是一个好的设计。

至于为什么,我不确定你在那里寻找什么答案。如果不允许,那么它将防止两个枚举引用相同值的情况。(我相信我可以很容易地想出这样有意义的例子。

因此,如果这是在限制我能做的事情或因为我通常不想要重复而受到限制之间做出选择,那么我会投票赞成这样做。

C++标准

第 7.2 节第 1 部分仅要求常量表达式为整型或枚举类型;不要求常量值是不同的。这为您提供了额外的灵活性来别名常量,如果您认为这会使您的代码更具表现力。例如

enum color {red=1,green=2,blue=3,max_color=3};
if (myColor > max_color) {/* report an error *}

优于

enum color {red=1,green=2,blue=3};
if (myColor > blue) {/* report an error *}

假设你已经开发了一个框架。此框架使用枚举进行参数化

出于某种原因,您对早期使用的术语不再满意。

仅仅替换该术语就会破坏现有软件。您决定提供新旧术语(至少一个发布周期)

是的,它是有效的。因为它不违反语言规范。以下内容引用自草案 N3242,正如您在示例中所看到的,与不同枚举器关联的值不必是不同的:

The identifiers in an enumerator-list are declared as constants, 
and can appear wherever constants are required. An enumeratordefinition
with = gives the associated enumerator the value indicated by the 
constant-expression. The constant-expression shall be an integral 
constant expression (5.19). If the first enumerator has no initializer,
the value of the corresponding constant is zero. An enumerator-definition without
an initializer gives the enumerator the value obtained by
increasing the value of the previous enumerator by one.
[ Example:
enum { a, b, c=0 };
enum { d, e, f=e+2 };
defines a, c, and d to be zero, b and e to be 1, and f to be 3. —end example ]
#include <iostream>
using namespace std;
enum color {blue, black=3, yellow=3};
int main()
{
    color a = blue;
    color b = black;
    color c = yellow;
    cout<<a<<endl;
    cout<<b<<endl;
    cout<<c<<endl;

        return 0;
}

使它们相同不是一个好主意。