Objective C - 何时应该使用“typedef”在“enum”之前,什么时候应该命名枚举?
在示例代码中,我看到了 this:
typedef enum Ename { Bob, Mary, John} EmployeeName;
和 this:
typedef enum {Bob, Mary, John} EmployeeName;
和 this:
typedef enum {Bob, Mary, John};
但对我来说成功编译的是:
enum {Bob, Mary, John};
我将该行放在 @interface 行上方的 .h 文件中,然后当我 #import 该 .h 文件到不同类的 .m 文件,那里的方法可以看到枚举。
那么,什么时候需要其他变体呢?
如果我可以将枚举命名为 EmployeeNames 之类的名称,然后当我键入“EmployeeNames”后跟“.”时,如果弹出一个列表显示枚举选项,那就太好了。
In sample code, I have seen this:
typedef enum Ename { Bob, Mary, John} EmployeeName;
and this:
typedef enum {Bob, Mary, John} EmployeeName;
and this:
typedef enum {Bob, Mary, John};
but what compiled successfully for me was this:
enum {Bob, Mary, John};
I put that line in a .h file above the @interface line, and then when I #import that .h file into a different class's .m file, methods there can see the enum.
So, when are the other variants needed?
If I could name the enum something like EmployeeNames, and then, when I type "EmployeeNames" followed by a ".", it would be nice if a list pops up showing what the enum choices are.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C(以及 Objective C)中,每次使用枚举类型时都必须以
enum
为前缀。通过创建 typedef:
您可以编写更短的:
替代声明在一个声明中声明枚举本身和 typedef。
In C (and hence Objective C), an enum type has to be prefixed with
enum
every time you use it.By making a typedef:
You can write the shorter:
The alternative declarations declare the enum itself and the typedef in one declaration.
enum { }
中的名称定义枚举值。当您给它一个名称时,您可以将它与关键字enum
一起用作类型,例如enum EmployeeName b = Bob;
。如果您还typedef
它,那么您可以在声明该类型的变量时删除enum
,例如EmployeeName b = Bob;
而不是前面的例子。The names inside
enum { }
define the enumerated values. When you give it a name, you can use it as a type together with the keywordenum
, e.g.enum EmployeeName b = Bob;
. If you alsotypedef
it, then you can drop theenum
when you declare variables of that type, e.g.EmployeeName b = Bob;
instead of the previous example.你的第三个例子与你的最后一个例子相同 -
typedef
没有用 - GCC 甚至给出了关于这种情况的警告:你的第一个和第二个例子也部分等效,因为它们都给出了枚举输入姓名
EmployeeName
。第一个示例还允许您将enum Ename
与EmployeeName
互换使用;在第二个示例中,EmployeeName
是唯一的选项。第二个示例必须按照您的方式编写 - 您可以按如下方式分解第一个示例:也许这有助于澄清问题?
Your third example is the same as your last example - the
typedef
there is useless - GCC even gives a warning about that case:Your first and second example are also partly equivalent, in that they both give the enum type a name
EmployeeName
. The first example also lets you useenum Ename
interchangeably withEmployeeName
; in the second example,EmployeeName
is the only option. The second example has to be written as you have - you can decompose the first example as follows:Maybe that helps clear things up?