How to avoid name conflicts for two enum values with the same name in C++?

前端 未结 5 1117
长发绾君心
长发绾君心 2020-12-14 21:06

Enums in C++ have one major problem: You can\'t have one name in two different enums like this:

enum Browser
{
    None = 0,
    Chrome = 1,
    Firefox = 2
         


        
5条回答
  •  [愿得一人]
    2020-12-14 21:32

    You can use enum class (scoped enums) which is supported in C++11 on up. It is strongly typed and indicates that each enum type is different.

    Browser::None != OS::None   
    
    enum class Browser
    {
        None = 0,
        Chrome = 1,
        Firefox = 2
    }
    
    enum class OS
    {
        None = 0,
        XP = 1,
        Windows7 = 2
    }
    

提交回复
热议问题