此枚举是否有效,如果有效,为什么
Is this enumeration valid, and if so, why?
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;
}
使它们相同不是一个好主意。
相关文章:
- 为什么是0;C++中的有效语句
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 为什么这种直接初始化有效?(C++17)
- 为什么在引用指针时将 const 放在 & 符号的左侧有效,而在右侧则无效?
- 为什么浮点数的矢量化比双精度更有效?
- 为什么模板参数中的双冒号有效?
- 为什么在这种情况下递增阵列名称有效?
- 为什么TinyXML2的XMLDocument::FirstChild()函数在尝试解析这个有效的XML文件时返回NULL?
- 这是什么代码?为什么它有效?C++
- 为什么别名声明不是有效的 init 语句(/simple-declaration)?
- 为什么在 C/C++ 中交织 switch/for/if 语句是有效的?
- 为什么这个复合语句作为用大括号和括号括起来的语句序列似乎不是有效的语句表达式
- 为什么使用不匹配的参数调用重载函数仍然有效
- 通过指针调用模板类成员函数 [为什么这是有效的 c++]?
- 为什么此代码片段有效?如何取消引用空点?
- 为什么 lambda nullptr 取消引用在这种情况下有效?
- std::map::emplace无法解决,但插入右值有效 - 为什么?
- 当程序从该函数调谐器时,指向在函数中声明和定义的某些 C 字符串的指针不再有效.为什么?
- 将浮点数分配给字符串引用有效 - 为什么
- Unicode字符或多字节字符:哪种类型更有效?为什么