【问题标题】:C++11 mixing enum class and unsigned int in switch case will not compileC ++ 11在switch case中混合枚举类和unsigned int将无法编译
【发布时间】:2015-03-09 17:14:08
【问题描述】:

为什么这段代码不能编译,我该怎么做才能让它编译?

#include <iostream>
using namespace std;

enum class myEnum : unsigned int
{
    bar = 3
};

int main() {
    // your code goes here

    unsigned int v  = 2;
    switch(v)
    {
        case 2:
        break;

        case myEnum::bar:
        break;
    }

    return 0;
}

ideone:

https://ideone.com/jTnVGq

prog.cpp: In function 'int main()':
prog.cpp:18:16: error: could not convert 'bar' from 'myEnum' to 'unsigned int'
   case myEnum::bar:

在 GCC 和 Clang 中构建失败,在 MSVC 2013 中工作。

【问题讨论】:

  • static_cast&lt;myEnum&gt;(2)
  • 强类型枚举是强类型,并且没有隐式转换为整数类型。
  • 我认为“:unsigned int”允许这样做?
  • 不,这只是意味着枚举将存储在无符号整数中。枚举本身仍然是强类型的。

标签: c++ c++11 enum-class


【解决方案1】:

enum class 的全部目的是使其成员无法直接与ints 进行比较,表面上提高了 C++11 相对于 C++03 的类型安全性。从enum class 中删除class,这将编译。

引用比亚恩勋爵的话:

(An)enum class(范围枚举)是一个enum,其中枚举数在枚举范围内,并且不提供到其他类型的隐式转换。

【讨论】:

  • 我敢说你夸大了“整体目的”。使用enum class 还有另一个原因——将枚举数限制在嵌套的命名空间中。
【解决方案2】:

继续使用enum class 的另一种方法是向myEnum 添加一个表示值2 的新字段。然后你可以把unsigned int v改成myEnum v

enum class myEnum : unsigned int
{
    foo = 2,
    bar = 3
};

int main() {
    myEnum v = myEnum::foo;
    switch(v)
    {
        case myEnum::foo:
        break;

        case myEnum::bar:
        break;
    }
}

【讨论】:

    【解决方案3】:

    你可以简单地使用这样的语法:

    enum class Test { foo = 1, bar = 2 };
    int main()
    {
      int k = 1;
      switch (static_cast<Test>(k)) {
        case Test::foo: /*action here*/ break;
      }
    }
    

    【讨论】:

      【解决方案4】:

      enum 使用类和 switch case 的示例,这是从另一个类调用 enum 类的正确方法。

      class MyClass 
      {
      public:
      
      enum class colors {yellow , blue , green} ; 
      
      };
      
      
      int main ()
      {
      
      Myclass::colors c = Myclass::colors::yellow;
       
      switch(c)
      {
      case Myclass::colors::yellow:
      cout <<"This is color yellow \n"
      case Myclass::colors::blue:
      cout <<"This is color blue\n"
      
      }
      
      return 0 ; 
      } 
      

      【讨论】:

      • 嗨,迈克,问题是问为什么它不能编译以及如何修复。也许编辑你的答案来解决这个问题。
      猜你喜欢
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 2012-04-01
      • 1970-01-01
      相关资源
      最近更新 更多