简体   繁体   English

使用和不使用'typedef'声明枚举之间有什么区别?

[英]What is the difference between declaring an enum with and without 'typedef'?

The standard way of declaring an enum in C++ seems to be: 在C ++中声明枚举的标准方法似乎是:

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? 哪一个是正确的?

C compatability. C兼容性。

In C, union , struct and enum types have to be used with the appropriate keyword before them: 在C中, unionstructenum类型必须与之前的相应关键字一起使用:

enum x { ... };

enum x var;

In C++, this is not necessary: 在C ++中,这不是必需的:

enum x { ... };

x var;

So in C, lazy programmers often use typedef to avoid repeating themselves: 所以在C语言中,懒惰的程序员经常使用typedef来避免重复:

typedef enum x { ... } x;

x var;

I believe the difference is that in standard C if you use 我相信不同的是,如果你使用标准C

enum <identifier> { list }

You would have to call it using 你必须使用它来调用它

enum <identifier> <var>;

Where as with the typedef around it you could call it using just 与其周围的typedef一样,你可以使用just来调用它

<identifier> <var>;

However, I don't think it would matter in C++ 但是,我认为它在C ++中并不重要

Similar to what @Chris Lutz said: 与@Chris Lutz所说的相似:

In old-C syntax, if you simply declared: 在old-C语法中,如果您只是声明:

 enum myEType { ... }; 

Then you needed to declare variables as: 然后你需要将变量声明为:

 enum myEType myVariable; 

However, if you use typedef: 但是,如果您使用typedef:

 typedef enum { ... } myEType; 

Then you could skip the enum-keyword when using the type: 然后,您可以在使用类型时跳过enum-keyword:

 myEType myVariable; 

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. C ++和相关语言已经废除了这个限制,但是在纯C环境中或者在C程序员编写时看到这样的代码仍然很常见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM