【问题标题】:Type of enum value not int?枚举值的类型不是 int?
【发布时间】:2017-11-26 21:22:00
【问题描述】:

由于 c++ 底层类型的 c++ 枚举应该是 int。

但是有代码

enum class Properties{ first , second }
void tmp ( int i ) {}

tmp( Properties::first )

编译器抱怨 Properties::first 不是 int 而不是 Properties 类型。

我真的必须将其转换为 int 才能将枚举值传递给函数还是有解决方法?

感谢您的帮助。

【问题讨论】:

标签: c++ c++11 enums


【解决方案1】:

Properties 是一个作用域枚举类型。那是因为您在定义它时使用了class 关键字。作用域枚举不能隐式转换为其基础类型(或任何整数类型,就此而言)。这是设计使然。

如果您想要转换,只需将其设为无范围枚举:

enum Properties{ first , second };

还有使用命名空间的妥协:

namespace Properties {
  enum { first , second };
}

这将通过完全限定的 id 为您提供所需的访问权限,同时保留隐式转换。

【讨论】:

    【解决方案2】:

    C++11 定义了enum 类(也称为作用域枚举),它使枚举具有强类型和强作用域。这是一个例子:

    #include <iostream>
    int main()
    {
        enum class Color // "enum class" defines this as an scoped enumeration instead of a standard enumeration
        {
            RED, // RED is inside the scope of Color
            BLUE
        };
    
        enum class Fruit
        {
            BANANA, // BANANA is inside the scope of Fruit
            APPLE
        };
    
        Color color = Color::RED; // note: RED is not directly accessible any more, we have to use Color::RED
        Fruit fruit = Fruit::BANANA; // note: BANANA is not directly accessible any more, we have to use Fruit::BANANA
    
        if (color == fruit) // compile error here, as the compiler doesn't know how to compare different types Color and Fruit
            std::cout << "color and fruit are equal\n";
        else
            std::cout << "color and fruit are not equal\n";
    
        return 0;
    }
    

    范围枚举表示:

    枚举器名称是 enum 的本地名称,并且它们的值不会隐式转换为其他类型。


    在您的情况下,您必须使用 enum 而不是 enum calss 来防止由于枚举范围引起的那种错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      • 2018-10-18
      • 2019-03-31
      • 2013-01-11
      • 2016-01-18
      • 2023-02-08
      相关资源
      最近更新 更多