如何在 C++ 中使用枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12183008/
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-27 15:58:21  来源:igfitidea点击:

How to use enums in C++

c++enums

提问by Rika

Suppose we have an enumlike the following:

假设我们有一个enum像下面这样的:

enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};

I want to create an instance of this enumand initialize it with a proper value, so I do:

我想创建一个实例enum并用适当的值初始化它,所以我这样做:

Days day = Days.Saturday;

Now I want to check my variable or instance with an existing enumvalue, so I do:

现在我想用现有enum值检查我的变量或实例,所以我这样做:

if (day == Days.Saturday)
{
    std::cout << "Ok its Saturday";
}

Which gives me a compilation error:

这给了我一个编译错误:

error: expected primary-expression before ‘.' token

错误:'.' 之前的预期主表达式 令牌

So to be clear, what is the difference between saying:

所以要清楚,说之间有什么区别:

if (day == Days.Saturday) // Causes compilation error

and

if (day == Saturday)

?

?

What do these two actually refer to, in that one is OK and one causes a compilation error?

这两个实际上指的是什么,一个是可以的,一个会导致编译错误?

回答by Mooing Duck

This code is wrong:

这段代码是错误的:

enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};
Days day = Days.Saturday;
if (day == Days.Saturday)

Because Daysis not a scope, nor object. It is a type. And Types themselves don't have members. What you wrote is the equivalent to std::string.clear. std::stringis a type, so you can't use .on it. You use .on an instanceof a class.

因为Days不是作用域,也不是对象。它是一种类型。而类型本身没有成员。你写的相当于std::string.clear. std::string是一种类型,所以你不能.在它上面使用。您.在类的实例上使用。

Unfortunately, enums are magical and so the analogy stops there. Because with a class, you can do std::string::clearto get a pointer to the member function, but in C++03, Days::Sundayis invalid. (Which is sad). This is because C++ is (somewhat) backwards compatable with C, and C had no namespaces, so enumerations had to be in the global namespace. So the syntax is simply:

不幸的是,枚举是神奇的,所以类比就到此为止了。因为用一个类,你可以做std::string::clear一个指向成员函数的指针,但是在C++03中,Days::Sunday是无效的。(这是可悲的)。这是因为 C++(在某种程度上)与 C 向后兼容,并且 C 没有命名空间,因此枚举必须在全局命名空间中。所以语法很简单:

enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};
Days day = Saturday;
if (day == Saturday)

Fortunately, Mike Seymourobserves that this has been addressed in C++11. Change enumto enum classand it gets its own scope; so Days::Sundayis not only valid, but is the onlyway to access Sunday. Happy days!

幸运的是,Mike Seymour发现 C++11 已经解决了这个问题。更改enumenum class并获得自己的范围;这样Days::Sunday不仅有效,而且是唯一的方式来访问Sunday。快乐的时光!

回答by mathematician1975

This will be sufficient to declare your enum variable and compare it:

这足以声明您的枚举变量并进行比较:

enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};
Days day = Saturday;
if (day == Saturday) {
    std::cout << "Ok its Saturday";
}

回答by pb2q

Much of this should give you compilation errors.

其中大部分应该会给你编译错误。

// note the lower case enum keyword
enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };

Now, Saturday, Sunday, etc. can be used as top-level bare constants,and Dayscan be used as a type:

现在, Saturday,Sunday等可以用作顶级裸常量,Days也可以用作类型:

Days day = Saturday;   // Days.Saturday is an error

And similarly later, to test:

同样稍后,测试:

if (day == Saturday)
    // ...

These enumvalues are like bare constants - they're un-scoped - with a little extra help from the compiler: (unless you're using C++11 enum classes) they aren'tencapsulated like object or structure members for instance, and you can't refer to them as membersof Days.

这些enum值就像裸常量 - 它们没有作用域 - 在编译器的一些额外帮助下:(除非您使用 C++11枚举类)它们不像对象或结构成员那样封装,并且你不能把它们称为成员Days

You'll have what you're looking for with C++11, which introduces an enum class:

您将拥有您正在寻找的C++11,它引入了一个enum class

enum class Days
{
    SUNDAY,
    MONDAY,
    // ... etc.
}

// ...

if (day == Days::SUNDAY)
    // ...

Note that this C++ is a little different from C in a couple of ways, one is that C requires the use of the enumkeyword when declaring a variable:

请注意,这个 C++ 在几个方面与 C 有点不同,一个是 Cenum在声明变量时需要使用关键字:

// day declaration in C:
enum Days day = Saturday;

回答by ataman1x

You can use a trick to use scopes as you wish, just declare enum in such way:

您可以根据需要使用一个技巧来使用范围,只需以这种方式声明枚举:

struct Days 
{
   enum type
   {
      Saturday,Sunday,Tuesday,Wednesday,Thursday,Friday
   };
};

Days::type day = Days::Saturday;
if (day == Days::Saturday)

回答by Dean Knight

Rather than using a bunch of if-statements, enums lend themselves well to switch statements

枚举不是使用一堆 if 语句,而是非常适合用于 switch 语句

I use some enum/switch combinations in the level builder I am building for my game.

我在为我的游戏构建的关卡构建器中使用了一些枚举/开关组合。

EDIT: Another thing, I see you want syntax similar to;

编辑:另一件事,我看到你想要类似的语法;

if(day == Days.Saturday)
etc

You can do this in C++:

你可以在 C++ 中做到这一点:

if(day == Days::Saturday)
etc

Here is a very simple example:

这是一个非常简单的例子:

EnumAppState.h

EnumAppState.h

#ifndef ENUMAPPSTATE_H
#define ENUMAPPSTATE_H
enum eAppState
{
    STARTUP,
    EDIT,
    ZONECREATION,
    SHUTDOWN,
    NOCHANGE
};
#endif

Somefile.cpp

一些文件.cpp

#include "EnumAppState.h"
eAppState state = eAppState::STARTUP;
switch(state)
{
case STARTUP:
    //Do stuff
    break;
case EDIT:
    //Do stuff
    break;
case ZONECREATION:
    //Do stuff
    break;
case SHUTDOWN:
    //Do stuff
    break;
case NOCHANGE:
    //Do stuff
    break;
}

回答by San

If you are still using C++03 and want to use enums, you should be using enums inside a namespace. Eg:

如果您仍在使用 C++03 并想使用枚举,则应该在命名空间内使用枚举。例如:

namespace Daysofweek{
enum Days {Saturday, Sunday, Tuesday,Wednesday, Thursday, Friday};
}

You can use the enum outside the namespace like,

您可以在命名空间之外使用枚举,例如,

Daysofweek::Days day = Daysofweek::Saturday;

if (day == Daysofweek::Saturday)
{
    std::cout<<"Ok its Saturday";
}

回答by Alex Byrth

You are looking for strongly typed enumerations, a feature available in the C++11standard. It turns enumerations into classes with scope values.

您正在寻找强类型枚举,这是C++11标准中可用的功能。它将枚举转换为具有范围值的类。

Using your own code example, it is:

使用您自己的代码示例,它是:

  enum class Days {Saturday, Sunday, Tuesday,Wednesday, Thursday, Friday};
  Days day = Days::Saturday;

  if (day == Days::Saturday)  {
    cout << " Today is Saturday !" << endl;
  }
  //int day2 = Days::Sunday; // Error! invalid

Using ::as accessors to enumerations will fail if targeting a C++ standard prior C++11. But some old compilers doesn't supported it, as well some IDEs just override this option, and set a old C++ std.

使用::作为访问器来枚举如果靶向C ++标准的现有C ++ 11将失败。但是一些旧的编译器不支持它,一些 IDE 只是覆盖了这个选项,并设置了一个旧的 C++ 标准。

If you are using GCC, enable C+11 with -std=c++11or -std=gnu11.

如果您使用 GCC,请使用-std=c++11-std=gnu11启用 C+11 。

Be happy!

要开心!

回答by bames53

This should not work in C++:

这不应该在 C++ 中工作:

Days.Saturday

Days is not a scope or object that contains members you can access with the dot operator. This syntax is just a C#-ism and is not legal in C++.

Days 不是包含您可以使用点运算符访问的成员的范围或对象。这种语法只是一种 C# 主义,在 C++ 中是不合法的。

Microsoft has long maintained a C++ extension that allows you to access the identifiers using the scope operator:

Microsoft 长期以来一直维护一个 C++ 扩展,允许您使用范围运算符访问标识符:

enum E { A, B, C };

A;
E::B; // works with Microsoft's extension

But this is non-standard before C++11. In C++03 the identifiers declared in an enum exist only in the same scope as the enum type itself.

但这在 C++11 之前是非标准的。在 C++03 中,枚举中声明的标识符仅存在于与枚举类型本身相同的范围内。

A;
E::B; // error in C++03

C++11 makes it legal to qualify enum identifiers with the enum name, and also introduces enum classes, which create a new scope for the identifiers instead of placing them in the surrounding scope.

C++11 使得使用枚举名称限定枚举标识符是合法的,并且还引入了枚举类,它为标识符创建一个新的作用域,而不是将它们放置在周围的作用域中。

A;
E::B; // legal in C++11

enum class F { A, B, C };

A; // error
F::B;

回答by InitializeSahib

While C++ (excluding C++11) has enums, the values in them are "leaked" into the global namespace.
If you don't want to have them leaked (and don't NEED to use the enum type), consider the following:

尽管 C++(不包括 C++11)具有枚举,但其中的值会“泄漏”到全局命名空间中。
如果您不想让它们泄露(并且不需要使用枚举类型),请考虑以下事项:

class EnumName {  
   public:   
      static int EnumVal1;  
      (more definitions)  
};  
EnumName::EnumVal1 = {value};  
if ([your value] == EnumName::EnumVal1)  ...

回答by Balázs édes

Enums in C++ are like integers masked by the names you give them, when you declare your enum-values (this is not a definition only a hint how it works).

当你声明你的枚举值时,C++ 中的枚举就像被你给它们的名字掩盖的整数(这不是一个定义,只是一个提示它是如何工作的)。

But there are two errors in your code:

但是您的代码中有两个错误:

  1. Spell enumall lower case
  2. You don't need the Days.before Saturday.
  3. If this enum is declared in a class, then use if (day == YourClass::Saturday){}
  1. 拼写enum全部小写
  2. 你不需要Days.星期六之前。
  3. 如果此枚举在类中声明,则使用 if (day == YourClass::Saturday){}