c – 为什么枚举类的默认类型与枚举的基础类型不同?

我问为什么以下代码在Visual Studio 2014更新4中产生错误.

enum A
{   a = 0xFFFFFFFF };

enum class B
{   b = 0xFFFFFFFF };

我知道我可以使用枚举类B:unsigned int.但为什么枚举的默认底层类型与枚举类的默认底层类型不同?应该有一个设计决定.

澄清
我忘了提到错误:

error C3434: enumerator value ‘4294967295’ cannot be represented as ‘int’, value is ‘-1’

这表明枚举类的默认底层类型是signed int,而默认类型的enum是unsigned int.这个问题是关于标志部分.

最佳答案
就N4140而言,MSVC是正确的:

§7.2/5 Each enumeration defines a type that is different from all
other types. Each enumeration also has an underlying type. The
underlying type can be explicitly specified using an enum-base. For
a scoped enumeration type, the underlying type is int if it is not
explicitly specified. […]

对于基本原理,您可以阅读标题为Strongly Typed Enums (Revision 3) N2347的提案.即,2.2.2可预测/可指定类型(特别是签名)解释了枚举的基础类型是实现定义的.例如,N4140再次:

§7.2/7 For an enumeration whose underlying type is not fixed, the
underlying type is an integral type that can represent all the
enumerator values defined in the enumeration. If no integral type can
represent all the enumerator values, the enumeration is ill-formed. It
is implementation-defined which integral type is used as the
underlying type except that the underlying type shall not be larger
than int unless the value of an enumerator cannot fit in an int or
unsigned int. If the enumerator-list is empty, the underlying type
is as if the enumeration had a single enumerator with value 0.

和N2347提出的解决方案:

This proposal is in two parts, following the EWG direction to date:

• provide a distinct new enum type having all the features that are
considered desirable:

o enumerators are in the scope of their enum

o enumerators and enums do not implicitly convert to int

o enums have a defined underlying type

  
  •为简单的枚举提供纯粹的向后兼容扩展
  这些功能的子集
  
  

o the ability to specify the underlying type

o the ability to qualify an enumerator with the name of the enum

  
  针对不同的新枚举类型提出的语法和措辞是
  基于此功能的C/C++LI [C/C++LI]语法.提议
  现有枚举扩展的语法是为相似性而设计的.

所以他们选择了解决方案,为scoped enums提供了一个定义的底层类型.

转载注明原文:c – 为什么枚举类的默认类型与枚举的基础类型不同? - 代码日志