什么是 Objective-C 中的 typedef 枚举? [英] What is a typedef enum in Objective-C?
问题描述
我不认为我从根本上理解 enum
是什么,以及何时使用它.
I don't think I fundamentally understand what an enum
is, and when to use it.
例如:
typedef enum {
kCircle,
kRectangle,
kOblateSpheroid
} ShapeType;
这里真正声明的是什么?
What is really being declared here?
推荐答案
这里声明了三件事:声明了一个匿名枚举类型,ShapeType
被声明为该匿名枚举的 typedef,以及三个名称 kCircle
、kRectangle
和 kOblateSpheroid
被声明为整数常量.
Three things are being declared here: an anonymous enumerated type is declared, ShapeType
is being declared a typedef for that anonymous enumeration, and the three names kCircle
, kRectangle
, and kOblateSpheroid
are being declared as integral constants.
让我们分解一下.在最简单的情况下,枚举可以声明为
Let's break that down. In the simplest case, an enumeration can be declared as
enum tagname { ... };
这声明了一个带有标签 tagname
的枚举.在C 和Objective-C(但不是 C++)中,对这个的任何引用都必须以enum
关键字开头.例如:
This declares an enumeration with the tag tagname
. In C and Objective-C (but not C++), any references to this must be preceded with the enum
keyword. For example:
enum tagname x; // declare x of type 'enum tagname'
tagname x; // ERROR in C/Objective-C, OK in C++
为了避免到处使用enum
关键字,可以创建一个typedef:
In order to avoid having to use the enum
keyword everywhere, a typedef can be created:
enum tagname { ... };
typedef enum tagname tagname; // declare 'tagname' as a typedef for 'enum tagname'
这可以简化为一行:
typedef enum tagname { ... } tagname; // declare both 'enum tagname' and 'tagname'
最后,如果我们不需要能够将 enum tagname
与 enum
关键字一起使用,我们可以制作 enum
匿名并且只用 typedef 名称声明它:
And finally, if we don't need to be able to use enum tagname
with the enum
keyword, we can make the enum
anonymous and only declare it with the typedef name:
typedef enum { ... } tagname;
现在,在本例中,我们将 ShapeType
声明为匿名枚举的 typedef 名称.ShapeType
实际上只是一个整数类型,并且应该只用于声明包含声明中列出的值之一的变量(即 kCircle
、kRectangle
和 kOblateSpheroid
).但是,您可以通过强制转换为 ShapeType
变量分配另一个值,因此在读取枚举值时必须小心.
Now, in this case, we're declaring ShapeType
to be a typedef'ed name of an anonymous enumeration. ShapeType
is really just an integral type, and should only be used to declare variables which hold one of the values listed in the declaration (that is, one of kCircle
, kRectangle
, and kOblateSpheroid
). You can assign a ShapeType
variable another value by casting, though, so you have to be careful when reading enum values.
最后,kCircle
、kRectangle
和 kOblateSpheroid
被声明为全局命名空间中的整数常量.由于没有指定特定的值,它们被分配给从 0 开始的连续整数,所以 kCircle
是 0,kRectangle
是 1,而 kOblateSpheroid
是2.
Finally, kCircle
, kRectangle
, and kOblateSpheroid
are declared as integral constants in the global namespace. Since no specific values were specified, they get assigned to consecutive integers starting with 0, so kCircle
is 0, kRectangle
is 1, and kOblateSpheroid
is 2.
这篇关于什么是 Objective-C 中的 typedef 枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!