如何:在 C++/CLI 中定义和使用枚举

本主题讨论在 C++/CLI 枚举。

指定枚举的基础类型

默认情况下,枚举的基础类型是 int。 但是,您可以指定类型要签名的或 int、short、long、__int32或 __int64的未签名的窗体。 还可以使用 char。

// mcppv2_enum_3.cpp
// compile with: /clr
public enum class day_char : char {sun, mon, tue, wed, thu, fri, sat};

int main() {
   // fully qualified names, enumerator not injected into scope
   day_char d = day_char::sun, e = day_char::mon;
   System::Console::WriteLine(d);
   char f = (char)d;
   System::Console::WriteLine(f);
   f = (char)e;
   System::Console::WriteLine(f);
   e = day_char::tue;
   f = (char)e;
   System::Console::WriteLine(f);
}

Output

  

如何转换在托管和标准枚举与

不在枚举和一个整数类型之间的标准转换;需要转换。

// mcppv2_enum_4.cpp
// compile with: /clr
enum class day {sun, mon, tue, wed, thu, fri, sat};
enum {sun, mon, tue, wed, thu, fri, sat} day2; // unnamed std enum

int main() {
   day a = day::sun;
   day2 = sun;
   if ((int)a == day2)
   // or...
   // if (a == (day)day2)
      System::Console::WriteLine("a and day2 are the same");
   else
      System::Console::WriteLine("a and day2 are not the same");
}

Output

  

运算符和枚举

下列运算符是有效的。在 C++/CLI 枚举:

运算符

! === < > <= >=

+ -

|^ & |

++ --

sizeof

运算符|^ & | C/C++--为枚举仅定义与集成基础类型,不包括 bool。 两个操作线程必须是枚举类型。

编译器不执行静态或动态检查枚举操作的结果;操作可能导致值不在枚举的有效的枚举数范围内。

备注

比在 C++/CLI 托管枚举选件类大大不同的 C++11 介绍枚举选件类输入非托管代码。具体而言,C++11 枚举选件类类型不支持运算符与托管枚举选件类输入 C++/CLI,并且,C++/CLI 源代码必须提供在托管枚举选件类声明的可访问性说明符为了与非托管 (C++11) 枚举选件类声明区分它们。有关枚举的更多信息在 C++/CLI,C++/CX 类别,并且,C++11,请参见 enum 类(C++ 组件扩展)

// mcppv2_enum_5.cpp
// compile with: /clr
private enum class E { a, b } e, mask;
int main() {
   if ( e & mask )   // C2451 no E->bool conversion
      ;

   if ( ( e & mask ) != 0 )   // C3063 no operator!= (E, int)
      ;

   if ( ( e & mask ) != E() )   // OK
      ;
}

// mcppv2_enum_6.cpp
// compile with: /clr
private enum class day : int {sun, mon};
enum : bool {sun = true, mon = false} day2;

int main() {
   day a = day::sun, b = day::mon;
   day2 = sun;

   System::Console::WriteLine(sizeof(a));
   System::Console::WriteLine(sizeof(day2));
   a++;
   System::Console::WriteLine(a == b);
}

Output

  

请参见

参考

enum 类(C++ 组件扩展)