简体   繁体   English

typedef和enum有什么区别

[英]What is the difference between typedef and enum

I am trying to use typedef and enum. 我正在尝试使用typedef和enum。 I have got two lines.Is there any difference between two following lines ? 我有两行。两行后面有什么区别吗?

typedef enum {UNDEFINED, POINT2D, POINT3D, CIRCLE, SQUARE, RECTANGLE, SPHERE} STYPE

enum STYPE {UNDEFINED, POINT2D, POINT3D, CIRCLE, SQUARE, RECTANGLE, SPHERE}
  • First line defines an enum with no tag, and gives it a name STYPE 第一行定义了一个没有标记的enum ,并为其命名为STYPE
  • Second line defines a named enum called STYPE 第二行定义了一个名为STYPE的命名enum

The difference is that the first enum does not have an enum tag, while the second one does. 区别在于第一个enum没有枚举标记,而第二个枚举没有。 In other words, both lines below will compile for enum STYPE 换句话说,下面的两行将编译为enum STYPE

STYPE s1;
enum STYPE s2;

while only the first line will compile for the typedef enum ... STYPE . 而只有第一行将为typedef enum ... STYPE编译typedef enum ... STYPE

Note: Using typedef is not common in C++, because enum defines a type name automatically. 注意:在C ++中使用typedef并不常见,因为enum自动定义类型名称。 The construct is more common in C, where enum without typedef must be used only as a tag, ie with enum keyword. 该构造在C中更常见,其中没有typedef enum必须仅用作标记,即使用enum关键字。 Finally, this construct is also used in C: 最后,这个结构也用在C中:

typedef enum STYPE {UNDEFINED, POINT2D, POINT3D, CIRCLE, SQUARE, RECTANGLE, SPHERE} STYPE;

It defines a tagged enum , and defines a type name for it. 它定义了标记的enum ,并为其定义了类型名称。 This declaration is also allowed in C++, but it is not different from your second declaration. C ++中也允许使用此声明,但它与您的第二个声明没有区别。

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

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