Suneet
Suneet

Reputation: 1

Enum scope is not accessible through structure in Class in C++

There is one problem I am facing in access and initializing the enum and structure as described There is one Header file defined as for sample.h have content as

class MyClass{

   enum M1 {
          MY_VAL1 = 0, 
          MY_VAL2,
          MY_VAL3
    };

   enum M2 {
          MY_VA1 = 0, 
          MY_VA2,
          MY_VA3
    };


   enum M3 {
          MY_V1 = 0, 
          MY_V2,
          MY_V3
    };

  struct val {
        M1 obj1;  
        M2 obj2;
        M3 obj3;
   };  

};

In the sample.cpp I am initializing or accessing as

#include "sample.h"

MyClass mObj = { {MY_VAL1}, {MY_VA1}, {MY_V1} };

But always complain about that "MY_VAL1", "MY_VA1", "MY_V1" not defined in the scope.

Upvotes: 0

Views: 397

Answers (2)

CIsForCookies
CIsForCookies

Reputation: 12817

All of these enums are not defined in the scope of main, instead they are defined inside your class. Use scope resolution operator (i.e. ::) to solve this. Note that using :: is still problematic in your case, since the enums are private. Change them to public for the :: to work.

... 
main(){
...
        int x = MyClass::MY_VA1;
...
    }

I'm not using your example, as it gives other errors...

Upvotes: 2

Toby Speight
Toby Speight

Reputation: 30831

Your enum types are not public, and you are not qualifying the member type names. It seems that you want some member variables, instead of declaring struct MyClass::val:

class MyClass{
public:
   enum M1 {
          MY_VAL1 = 0, 
          MY_VAL2,
          MY_VAL3
    };

   enum M2 {
          MY_VA1 = 0, 
          MY_VA2,
          MY_VA3
    };


   enum M3 {
          MY_V1 = 0, 
          MY_V2,
          MY_V3
    };

    M1 obj1;
    M2 obj2;
    M3 obj3;
};

static const MyClass foo = { MyClass::MY_VAL1, MyClass::MY_VA1, MyClass::MY_V1 };

Upvotes: 3

Related Questions