user1406186
user1406186

Reputation: 1002

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;
}
}

Upvotes: 0

Views: 1365

Answers (4)

Meena Alfons
Meena Alfons

Reputation: 1230

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 state_region::ACT to access it:

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;
}
}

Upvotes: 0

Wojtek Marczenko
Wojtek Marczenko

Reputation: 36

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).

Upvotes: 0

bibilouis
bibilouis

Reputation: 63

"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.

Upvotes: 4

bunty
bunty

Reputation: 629

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;
}

Upvotes: 0

Related Questions