How to use enums in C++

前端 未结 14 691
臣服心动
臣服心动 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

    Rather than using a bunch of if-statements, enums lend themselves well to switch statements

    I use some enum/switch combinations in the level builder I am building for my game.

    EDIT: Another thing, I see you want syntax similar to;

    if(day == Days.Saturday)
    etc
    

    You can do this in C++:

    if(day == Days::Saturday)
    etc
    

    Here is a very simple example:

    EnumAppState.h

    #ifndef ENUMAPPSTATE_H
    #define ENUMAPPSTATE_H
    enum eAppState
    {
        STARTUP,
        EDIT,
        ZONECREATION,
        SHUTDOWN,
        NOCHANGE
    };
    #endif
    

    Somefile.cpp

    #include "EnumAppState.h"
    eAppState state = eAppState::STARTUP;
    switch(state)
    {
    case STARTUP:
        //Do stuff
        break;
    case EDIT:
        //Do stuff
        break;
    case ZONECREATION:
        //Do stuff
        break;
    case SHUTDOWN:
        //Do stuff
        break;
    case NOCHANGE:
        //Do stuff
        break;
    }
    

提交回复
热议问题