使用和不使用“typedef”声明枚举有什么区别?
在 C++ 中声明枚举的标准方法似乎是:
enum <identifier> { <list_of_elements> };
但是,我已经看到了一些声明,例如:
typedef enum { <list_of_elements> } <identifier>;
它们之间有什么区别(如果存在)?哪一个是正确的?
The standard way of declaring an enum in C++ seems to be:
enum <identifier> { <list_of_elements> };
However, I have already seen some declarations like:
typedef enum { <list_of_elements> } <identifier>;
What is the difference between them, if it exists? Which one is correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C 兼容性。
在 C 中,
union
、struct
和enum
类型必须在它们之前使用适当的关键字:在 C++ 中,这是不必要的:
所以在 C 语言中,懒惰的程序员经常使用 typedef 来避免重复:
C compatability.
In C,
union
,struct
andenum
types have to be used with the appropriate keyword before them:In C++, this is not necessary:
So in C, lazy programmers often use
typedef
to avoid repeating themselves:我相信区别在于,在标准 C 中,如果你使用
你将不得不使用它来调用它
,而与它周围的 typedef 一样,你可以使用它来调用它
但是,我认为这在 C++ 中并不重要
I believe the difference is that in standard C if you use
You would have to call it using
Where as with the typedef around it you could call it using just
However, I don't think it would matter in C++
类似于 @Chris Lutz 所说的:
在旧的 C 语法中,如果您简单地声明:
然后您需要将变量声明为:
但是,如果您使用 typedef:
然后你可以在使用类型时跳过枚举关键字:
C++ 和相关语言已经取消了这一限制,但在纯 C 环境中或由 C 程序员编写的代码中仍然常见这样的代码。
Similar to what @Chris Lutz said:
In old-C syntax, if you simply declared:
Then you needed to declare variables as:
However, if you use typedef:
Then you could skip the enum-keyword when using the type:
C++ and related languages have done away with this restriction, but its still common to see code like this either in a pure C environment, or when written by a C programmer.