user1697693
user1697693

Reputation: 13

How to access enum from a header file in CPP

Details: C++, gcc compiler.

Say I have a headerfile with some

    :
class  myClass {
   public: 
    enum color {red, blue};
    :

how do I set the variable color in my source file where i included the file and have declared

myClass T;

for some reason

I cannot set it as T.color = red;

I get

error: cannot refer to type member ‘color’ in
      ‘something::myClass’ with '.'
  T.color = red;
    ^
<path of header file>:77:7: note: 
      member ‘color’ declared here
        enum color {red, blue};
             ^

I know I am doing something wrong here.. it will be a lot of help if someone could tell me what.

Upvotes: 1

Views: 2952

Answers (1)

Bryan Chen
Bryan Chen

Reputation: 46608

enum color {red, blue}; define a type enum color but not a field color. you need to declare a field either by enum color field; or enum {red, blue} color;

here is the code works

class  myClass {
   public: 
    enum color_t {red, blue};
    enum color_t color;
    // enum {red, blue} color; // or this
};

int main() {
    myClass my;
    my.color = myClass::red;
    my.color = myClass::blue;
    return 0;
}

Upvotes: 2

Related Questions