How to use enums in C++

前端 未结 14 499
臣服心动
臣服心动 2020-12-04 04:30

Suppose we have an enum like the following:

enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};

I want to crea

相关标签:
14条回答
  • 2020-12-04 05:26

    This should not work in C++:

    Days.Saturday
    

    Days is not a scope or object that contains members you can access with the dot operator. This syntax is just a C#-ism and is not legal in C++.

    Microsoft has long maintained a C++ extension that allows you to access the identifiers using the scope operator:

    enum E { A, B, C };
    
    A;
    E::B; // works with Microsoft's extension
    

    But this is non-standard before C++11. In C++03 the identifiers declared in an enum exist only in the same scope as the enum type itself.

    A;
    E::B; // error in C++03
    

    C++11 makes it legal to qualify enum identifiers with the enum name, and also introduces enum classes, which create a new scope for the identifiers instead of placing them in the surrounding scope.

    A;
    E::B; // legal in C++11
    
    enum class F { A, B, C };
    
    A; // error
    F::B;
    
    0 讨论(0)
  • 2020-12-04 05:29

    You can use a trick to use scopes as you wish, just declare enum in such way:

    struct Days 
    {
       enum type
       {
          Saturday,Sunday,Tuesday,Wednesday,Thursday,Friday
       };
    };
    
    Days::type day = Days::Saturday;
    if (day == Days::Saturday)
    
    0 讨论(0)
提交回复
热议问题