代码之家  ›  专栏  ›  技术社区  ›  Rick Jim DeLaHunt

为什么不能直接创建作用域枚举类成员,而可以创建非作用域枚举类成员?

c++
  •  1
  • Rick Jim DeLaHunt  · 技术社区  · 7 年前

    cout unscoped enum直接工作:

    #include <iostream>
    using namespace std;
    enum  color { red, green, blue };
    
    int main()
    {
        cout << color::green;
        return 0;
    }
    

    使用socoped枚举时不能:

    #include <iostream>
    using namespace std;
    enum class color { red, green, blue };
    
    int main()
    {
        cout << color::green;
        return 0;
    }
    

    有什么区别?

    3 回复  |  直到 7 年前
        1
  •  4
  •   Brian Bi    7 年前

    这是因为非作用域枚举可以隐式转换为整数,而作用域枚举则不能,并且需要显式转换:

    cout << static_cast<int>(color::green);
    
        2
  •  1
  •   Max Langhof    7 年前

    非作用域枚举将自动转换为某种整数类型。所以只能打印出来 1 ,不是 green .

    作用域枚举不能隐式转换为整数,并且没有其他类型的枚举 operator<< 对于 std::cout 所以它无法编译。

        3
  •  0
  •   Nikola Lukic    7 年前

    也许char-like-optimal属性对你有帮助。

    #include <iostream>
    
    using namespace std;
    
    enum class Color { red='r', green='g', blue='b' };
    
    int main()
    {
    
        cout << "Print opt attribute: " <<  static_cast<char>(Color::green);
        return 0;
    }
    

    https://onlinegdb.com/Syw-qgg97