Why do you use typedef when declaring an enum in C++?

后端 未结 9 837
别那么骄傲
别那么骄傲 2020-11-30 17:39

I haven\'t written any C++ in years and now I\'m trying to get back into it. I then ran across this and thought about giving up:

typedef enum TokenType
{
            


        
9条回答
  •  Happy的楠姐
    2020-11-30 18:17

    You do not need to do it. In C (not C++) you were required to use enum Enumname to refer to a data element of the enumerated type. To simplify it you were allowed to typedef it to a single name data type.

    typedef enum MyEnum { 
      //...
    } MyEnum;
    

    allowed functions taking a parameter of the enum to be defined as

    void f( MyEnum x )
    

    instead of the longer

    void f( enum MyEnum x )
    

    Note that the name of the typename does not need to be equal to the name of the enum. The same happens with structs.

    In C++, on the other hand, it is not required, as enums, classes and structs can be accessed directly as types by their names.

    // C++
    enum MyEnum {
       // ...
    };
    void f( MyEnum x ); // Correct C++, Error in C
    

提交回复
热议问题