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.
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.
@itmanwork You can declare an enum instance inside a struct, but you cannot use typedef.
Inheritance Is Not Allowed for Enums.
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.
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, butEnum2::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.
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.
You don't need the name of the enum, but you are on the right track:
LineChartScene::LineChartSceneImpl::ShowLabels
Just LineChartScene::LineChartSceneImpl::ShowLabels
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With