枚举器在c ++中的实现

时间:2014-01-25 06:06:57

标签: enumeration c++03 enumerator

我知道枚举类型的实现依赖于枚举器的值,编译器选择一个可以代表所有枚举器值的类型,在下面的例子中我不知道为什么 example1 没有&# 39; t编译,而 example2 编译好吗?

注意:
那个大数字不仅仅是一个随机数,它完全是pow(2,63),我无法在那里使用它,因为枚举数只能用整数常量表达式初始化。
9223372036854775808 = pow(2,63)



example1.1:

enum A{a=9223372036854775808,b=-1};

cout << sizeof(a) << endl; 

错误:没有整数类型可以表示&#39; main():: A&#39;

的所有枚举值 example1.2:

enum A{a=9223372036854775808,b=-9223372036854775807};

cout << sizeof(a) << endl;

b=-( pow(2,63) - 1 )
这也给了我同样的错误,没有整数类型可以代表A的所有枚举值。


例2:

enum A{a=9223372036854775808,b=-9223372036854775808};

cout << sizeof(a) << endl; // prints 8

这个编译没有任何错误,并打印sizeof(a),即8。


上述行为是否有任何解释?


更新
如果您使用Coliru编译上面的代码,它会编译而不会出错,因为它有一个16字节长的整数类型,因此将a的值更改为pow(2,127)-1和{ {1}}到b会再次出现同样的错误。为了防止混淆,为了这个例子,让我们坚持使用32位机器,以便在线编译器使用Ideone

我的问题很清楚,为什么-1会有效,而b=-9223372036854775808则不然?

UPDATE2:

请注意, example2 c++11 comipler)不能使用c ++ 11进行编译,在我看来这是合乎逻辑的事情。但是在c ++ 03 example2 c++03 compiler)中编译很好,但是 example1 没有编译。

1 个答案:

答案 0 :(得分:1)

我的错误是在C ++ 11模式下编译,因此无法重现错误。但是现在我切换到C++03 mode,我可以重现问题并且错误也不同:

main.cpp:5:10: warning: integer constant is too large for its type [enabled by default]

 enum A{a=170141183460469231731687303715884105727,b=-1};

          ^

main.cpp:5:1: warning: this decimal constant is unsigned only in ISO C90 [enabled by default]

 enum A{a=170141183460469231731687303715884105727,b=-1};

 ^

main.cpp:5:1: warning: integer constant is too large for 'long' type [-Wlong-long]

main.cpp:5:54: error: no integral type can represent all of the enumerator values for 'A'

 enum A{a=170141183460469231731687303715884105727,b=-1};

                                                      ^

main.cpp:5:8: warning: large integer implicitly truncated to unsigned type [-Woverflow]

 enum A{a=170141183460469231731687303715884105727,b=-1};

看看最后一个。如果它被截断为无符号类型,则说明存在编译器错误(因为b为-1)。例如#2,截断doesn't seem to happen