Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing enum values defined in a struct

If I have the following:

struct LineChartScene::LineChartSceneImpl
{
    enum ContextMenuAction {ShowLabels, ShowPoints, SaveAsImage};
};

How can I access ShowLabels, ShowPoints etc outside LineChartScene::LineChartSceneImpl struct? I thought LineChartScene::LineChartSceneImpl::ContextMenuAction::ShowLabels would work but it doesn't. I'm using C++, Qt Creator 2.2.1.

like image 633
Donotalo Avatar asked Nov 21 '11 14:11

Donotalo


People also ask

Can enum be in a struct?

Enum in C# can be declared within or outside class and structs. Enum constants has default values which starts from 0 and incremented to one by one.

Can we declare enum inside structure?

@itmanwork You can declare an enum instance inside a struct, but you cannot use typedef.

Can you inherit enums?

Inheritance Is Not Allowed for Enums.

Is enum a class or struct?

Coming from an objective c background, the difference between components like enums, classes, and structs was quite obvious for me: An Enum is a set of named values, Struct is structured data type, and of course Class allows us to create objects with all POO related stuff.


4 Answers

struct LineChartScene::LineChartSceneImpl
{
    enum ContextMenuAction {ShowLabels, ShowPoints, SaveAsImage};
};

use it as

LineChartScene::LineChartSceneImpl::ShowLabels

For your info, C++11 also has strong typed enums with precisely the namespace semantics you expected:

enum class Enum2 : unsigned int {Val1, Val2};

The scoping of the enumeration is also defined as the enumeration name's scope. Using the enumerator names requires explicitly scoping. Val1 is undefined, but Enum2::Val1 is defined.

Additionally, C++11 will allow old-style enumerations to provide explicit scoping as well as the definition of the underlying type:

enum Enum3 : unsigned long {Val1 = 1, Val2};

The enumerator names are defined in the enumeration's scope (Enum3::Val1), but for backwards compatibility, enumerator names are also placed in the enclosing scope.

like image 79
sehe Avatar answered Nov 04 '22 09:11

sehe


Use :

LineChartScene::LineChartSceneImpl::ShowLabels

Notice that there is noContextMenuAction in the line. It is because the enum labels are not scoped within the enum type, rather they are scoped within the enclosing scope in which the enum is defined, and in this case the enclosing scope is the class type. I know it is very unintuitive, but that is how it is designed.

like image 33
Nawaz Avatar answered Nov 04 '22 10:11

Nawaz


You don't need the name of the enum, but you are on the right track:

LineChartScene::LineChartSceneImpl::ShowLabels
like image 33
trojanfoe Avatar answered Nov 04 '22 09:11

trojanfoe


Just LineChartScene::LineChartSceneImpl::ShowLabels

like image 26
zennehoy Avatar answered Nov 04 '22 11:11

zennehoy