简体   繁体   中英

c++ switch enum error

I'm making a simple switch function using enums, however i'm getting the error 'ACT' undefined identifier. in AS.cpp. Not sure what i'm doing wrong here...

If you could please help explain why I am getting this error that'd be great. THankyou

//AS.h

#ifndef AS_H
#define AS_H

class AS {
private:
    enum class state_region;

public:

    int determine_FDI(state_region selected_state_region);
};

#endif



/////////AS.cpp
        #include "AS.h"

enum class state_region {ACT};

int AS::determine_FDI(state_region selected_state_region) {
    int FDI;

    switch (selected_state_region) {
    case ACT:
        FDI = 100;
        break;
}
}

"enum class" introduced in C++11 is also called "scoped enumeration".

This clearly highlights the difference with "enum", enum values are now living in a dedicated scope.

You need to add the scope to your "case" like this:

case state_region::ACT:

instead of

case ACT:

This last line is looking for ACT identifier in your current scope but it fails to find it, hence the error.

The following code worked correctly:

/////////AS.cpp
#include "AS.h"

enum class AS::state_region {ACT};

int AS::determine_FDI(state_region selected_state_region) {
    int FDI;

    switch (selected_state_region) {
        case state_region::ACT:
            FDI = 100;
            break;
    }

    return 0;
}

With enum class as opposed to traditional enums , the enum values are scoped inside of it, which means you have to use them like this: state_region::ACT . The advantage of having to do this is that now multiple enums can use the same value names.

Also, the way you define state_region in cpp file makes it a new enum in global scope. To properly define the one that you declared inside of the class, use enum class AS::state_region {ACT}; (the same way you define methods and static fields).

First, enum class state_region inside class AS is not defined. See comments:

/////////AS.cpp
#include "AS.h"

// This defines ::state_region in the global scope
//enum class state_region {ACT};

// This is the definition of AS::state_region
enum class AS::state_region {ACT};

Second, the enumerators of enum class are not available in the global scope. You need to use ACT to access it: ACT来访问它:

int AS::determine_FDI(state_region selected_state_region) {
    int FDI;

    switch (selected_state_region) {
    case state_region::ACT:           // <-- state_region:: required
        FDI = 100;
        break;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM