mercredi 12 mai 2021

initializing enum with a constructor

I already found this really good explanation Initialising enum via constructors but it didn't fit my needs.

So I declare an enum inside a class and want to initialize it inside the class constructor and then call this enum via a switch statement inside a method but I'm not able to implement it. Here is a code:

    class myClass {
        
        myClass();
        
        enum class State;

        void update();

        };
    
    
    //  initialise State() with default value, so state1=0, state2=1
    myClass::myClass() : State() {} 
    
    enum class
        myClass::State
        {
            state1,
            state2
        } enumState;
    
    
    
    
    void myClass::update(){
    
    switch (enumState){
    
    case enumState.state1:
         break;
    case enumState.state2:
         break;

    }
}

But obviously it is not the correct way to implement it.

I get these errors:

error: ‘enum class myClass::State’ is not a non-static data member of ‘myClass’

error: request for member ‘state1’ in ‘enumState’, which is of non-class type ‘myClass::State’

Can someone explain me how to implement such a code and what if I want to initialise State with default parameter ?

Thank you !

Aucun commentaire:

Enregistrer un commentaire