C++ 访问结构中定义的枚举值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8213696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:11:15  来源:igfitidea点击:

Accessing enum values defined in a struct

c++qtenumsstructresolution

提问by Donotalo

If I have the following:

如果我有以下几点:

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

How can I access ShowLabels, ShowPointsetc outside LineChartScene::LineChartSceneImplstruct? I thought LineChartScene::LineChartSceneImpl::ContextMenuAction::ShowLabelswould work but it doesn't. I'm using C++, Qt Creator 2.2.1.

如何访问ShowLabelsShowPoints等外面LineChartScene::LineChartSceneImpl结构?我以为LineChartScene::LineChartSceneImpl::ContextMenuAction::ShowLabels会工作,但它没有。我正在使用 C++,Qt Creator 2.2.1。

回答by sehe

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

use it as

用它作为

LineChartScene::LineChartSceneImpl::ShowLabels

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

对于您的信息,C++11 还具有强类型枚举,具有您所期望的命名空间语义:

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. Val1is undefined, but Enum2::Val1is 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.

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

枚举的范围也定义为枚举名称的范围。使用枚举器名称需要明确的范围。Val1未定义,但Enum2::Val1已定义。

此外,C++11 将允许旧式枚举提供显式范围以及底层类型的定义:

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

枚举器名称在枚举的范围 ( Enum3::Val1)中定义,但为了向后兼容,枚举器名称也放置在封闭范围内。

回答by Nawaz

Use :

用 :

LineChartScene::LineChartSceneImpl::ShowLabels

Notice that there is noContextMenuActionin 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.

请注意,ContextMenuAction该行中没有。这是因为枚举标签不在 enum type范围内,而是在定义枚举的封闭范围内范围内,在这种情况下,封闭范围是类类型。我知道这很不直观,但这就是它的设计方式。

回答by trojanfoe

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

您不需要枚举的名称,但您走在正确的轨道上:

LineChartScene::LineChartSceneImpl::ShowLabels

回答by zennehoy

Just LineChartScene::LineChartSceneImpl::ShowLabels

只是 LineChartScene::LineChartSceneImpl::ShowLabels