Reputation: 339
I am getting an error with a program. Evidently I'm missing something about the syntax. The snippet of C++ code below is the smallest which produces the error.
#include <iostream>
using namespace std;
class Parent
{
public:
enum MyEnum {
Value1,
Value2,
Value3
};
MyEnum* set;
};
class Child: public Parent
{
public:
Child()
{
set = new MyEnum[5];
set[0]=MyEnum.Value1;//<--Something wrong here
set[1]=MyEnum.Value2;//<--Something wrong here
set[2]=MyEnum.Value3;//<--Something wrong here
set[3]=MyEnum.Value2;//<--Something wrong here
set[4]=MyEnum.Value1;//<--Something wrong here
}
void Write()
{
for(int i=0;i<5;i++)
{
cout<< "This is " << i << ": " << set[i];
}
}
};
int main() {
Child c;
c.Write();
return 0;
}
The error has something to do with the indicated syntax.
expected primary-expression before ‘.’ token
I have tried Parent.MyEnum.Value1, Parent::MyEnum.Value1, etc. nothing seems to be right. How should I be referring to the specific values in the parent class?
Upvotes: 0
Views: 1091
Reputation: 7433
An enum
, like a class
, defines a scope. A regular enum like you use puts its enumerator names both in its own scope and its containing scope. Since this is scope resolution, not member access, you use ::
instead of .
. Therefore, you can use Parent::Value1
, Value1
(because public
and protected
names of Parent
are visible in Child
), or Parent::MyEnum::Value1
or MyEnum::Value1
.
If you want to disallow the first or two options, you should use enum class
instead of just enum
.
Upvotes: 1
Reputation: 8501
Enums don't require qualification for their values, meaning you should access them like this:
set[0] = Parent::Value1;
If you would like to enforce qualification, you can use strongly typed enums. It looks like this:
enum struct MyEnum {
Value1,
Value2,
Value3
};
set[0] = Parent::MyEnum::Value1;
But then you should print them using an explicit cast, e.g:
cout << static_cast<int>(set[0]) << endl;
Upvotes: 3