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

C++/CLI 中的枚举类型与标准 C++ 中的枚举类型存在一些差异。 本文介绍如何使用 C++/CLI 枚举类型以及如何与标准枚举类型进行互操作。

指定 enum 的基础类型

默认情况下,枚举的基础类型为 int。 但是,可以指定要签名的类型或 intshortlong__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);
}

输出

sun
0
1
2

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

枚举类型和整型类型之间没有标准转换;需要进行强制转换。

// 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");
}

输出

a and day2 are the same

运算符和枚举

以下运算符对 C++/CLI 中的枚举有效:

运算符
== != < > <= >=
+ -
| ^ & ~
++ --
sizeof

运算符 |^&~++-- 仅为具有整型基础类型的枚举定义,不包括 bool。 两个操作数都必须是枚举类型。

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

注意

C++11 在非托管代码中引入了 enum class 类型,这与 C++/CLI 中的托管 enum class 类型有很大不同。 特别是,C++11 enum class 类型不支持与 C++/CLI 中的托管 enum class 类型相同的运算符,并且 C++/CLI 源代码必须在托管 enum class 声明中提供可访问性说明符,以便将它们与非托管 (C++11) enum class 声明区分开来。 有关在 C++/CLI、C++/CX 和 C++11 中使用 enum class 的详细信息,请参阅 enum class

// 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
      ;
}

使用范围限定符区分 enumenum class 值:

// 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);
}

输出

4
1
True

另请参阅

enum class