C++ typedef enum 和 enum
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9893048/
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
C++ typedef enum and just enum
提问by Nickoleta Dimitrova
What exactly is the difference between:
究竟有什么区别:
typedef enum {
something1,
something2,
.....
somethingN
} myEnum;
end just
刚结束
enum myEnum{
something1,
something2,
.....
somethingN
};
I know in first case I have typedefed unnamed enum, of course, just wonder which approach is better and why?
我知道在第一种情况下我已经对未命名的枚举进行了 typedefed,当然,只是想知道哪种方法更好,为什么?
回答by Oliver Charlesworth
The first variant was useful in C, because otherwise you would have to write enum myEnum
everywhere you wished to use it.
第一个变体在 C 中很有用,否则您将不得不在enum myEnum
任何想要使用它的地方编写代码。
This is not the case in C++. So, AFAIK, there is no benefit to the first case in C++ (unless you're defining e.g. an interface that needs to be shared with C).
在 C++ 中不是这种情况。因此,AFAIK,C++ 中的第一种情况没有任何好处(除非您定义了例如需要与 C 共享的接口)。
回答by Nawaz
No difference. In fact, the first version is C-style coding.
没有不同。事实上,第一个版本是 C 风格的编码。
C++11 has introduced stronly-typed enum, which you define as:
C++11 引入了stronly-typed enum,您将其定义为:
enum class myEnum //note the 'class' keyword after the 'enum' keyword
{
something1,
something2,
.....
somethingN
};
In C++03, enums are not type-safe, they're essentially integers, and can mix with other integral types implicitly, and another problem with them is that they don't have scope; you can use its member without qualifying its type; you can use something1
. Whereas C++11 strongly-typed enums are type-safe, and they've scope; you've to use myEnum::something1
.
在 C++03 中,枚举不是类型安全的,它们本质上是整数,并且可以隐式地与其他整数类型混合,它们的另一个问题是它们没有作用域;您可以在不限定其类型的情况下使用其成员;你可以使用something1
. 而 C++11 强类型枚举是类型安全的,并且它们有作用域;你必须使用myEnum::something1
.
回答by R. Martinho Fernandes
I wouldn't use the first one. It is almostthe same as the other one. In C++11, with the second you can write myEnum::something1
but not with the first one. Also in C++11, you can forward declare enums in some cases, but it is impossible to do forward declarations of unamed types and you can't forward declare typedefs either.
我不会使用第一个。它与另一个几乎相同。在 C++11 中,第二个你可以写,myEnum::something1
但第一个不行。同样在 C++11 中,您可以在某些情况下转发声明枚举,但无法进行未命名类型的转发声明,也不能转发声明类型定义。