Enum and Euma Class

1.Enum

 Enum Day{
    
    Mon=1,Tus,Wen,Thu,Fri,Sat,Sun};//Day 枚举名(域名)
 Enum Day day;//Day的对象名
 day=mon;//day=1;
 ++day;//1+1
 cout<<day<<endl;//cout 2

//

Enum Day{
    
    Mon=6,Tus,Wen,Thu,Fri,Sat,Sun} day;//定义对象名
day=Tus;//7
++day;//8
cout<<day;//8

Enum is essentially an integer type, a scope, common to c and c++

2.Enum Class

1. Under what circumstances are enumeration classes used?

Sometimes the objects of a class are limited and fixed. In this case, it is more convenient for us to use enumeration classes

2. Why not use static constants instead of enumeration classes?

static int SEASON_SPRING = 1;
static int SEASON_SUMMER = 2;
static int SEASON_FALL = 3;
static int SEASON_WINTER = 4;

Enumeration classes are more intuitive and type safe . The use of constants has the following disadvantages:

1. The type is not safe . If a method requires the season parameter to be passed in, if a constant is used, the formal parameter is of type int. Developers can pass in any type of int type value, but if it is an enumeration type, it can only be passed to the enumeration class Included objects.

2. There is no namespace . Developers should start with SEASON_ when naming them, so that when another developer looks at this code, they will know that these four constants represent the seasons.

3. Enum Class and union

Union is used to match the corresponding enumeration type in the structure.

enum Type{
    
    str,num};

union Value{
    
    
char* s;
int i;
}

struct Entry{
    
    
char* name;
Type t;
Value v;
};

void f(Entry *p)
{
    
    
if(p->t==str)
{
    
    cout<<p->v.s;}
}

Part of the link description is added from the blog of the fish who eats sheep . Although it is java, it is also very suitable for C++.

Guess you like

Origin blog.csdn.net/guanxunmeng8928/article/details/108396811