typedef struct 和 enum,为什么?
在我维护的代码中,我经常看到以下内容
typedef enum { blah, blah } Foo;
typedef struct { blah blah } Bar;
: of:
enum Foo { blah, blah };
struct Bar { blah blah };
我一直用后者,这是我第一次看到前者。所以问题是为什么人们会使用一种风格而不是另一种风格。有什么好处吗?它们的功能也相同吗?我相信他们是,但不是 100% 确定。
Possible Duplicates:
Purpose of struct, typedef struct, in C++
typedef struct vs struct definitions
In code that I am maintaining I often see the following:
typedef enum { blah, blah } Foo;
typedef struct { blah blah } Bar;
Instead of:
enum Foo { blah, blah };
struct Bar { blah blah };
I always use the latter, and this is the first time I am seeing the former. So the question is why would one use one style over the other. Any benefits? Also are they functionally identical? I believe they are but am not 100% sure.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 C++ 中这并不重要。
在 C 中,
struct
、enum
和union
位于不同的“命名空间”中,这意味着它们的名称可能与变量名称冲突。如果您说So,您可以这样说
,这意味着 struct S 是数据类型,S 是变量名称。 你不能在 C 中说
如果
S
是一个struct
(而不是类型名称), ,所以人们只是使用typedef
来避免说 <代码>结构始终。In C++ this doesn't matter.
In C,
struct
s,enum
s, andunion
s were in a different "namespace", meaning that their names could conflict with variable names. If you saySo you could say something like
and that would mean that
struct S
is the data type, andS
is the variable name. You couldn't sayin C if
S
was astruct
(and not a type name), so people just usedtypedef
to avoid sayingstruct
all the time.它们是为了 C 兼容性。 A 法线
与 C 的作用不同;
They are for C compatability. A normal
doesn't work the same with C;