typedef struct vs struct definitions

在C ++中,只有细微的差别。这是C的遗留物,在其中有所作为。

C语言标准(C89§3.1.2.3C99§6.2.3C11§6.2.3)为不同类别的标识符(包括标记标识符(用于structunionenum)和普通标识符(for typedef和其他标识符))规定了单独的命名空间。。

如果您只是说:

struct Foo { ... };
Foo x;

您将得到一个编译器错误,因为Foo它仅在标记名称空间中定义。

您必须将其声明为

struct Foo x;

每当您要引用a时Foo,都必须始终将其称为struct Foo。快速变得烦人,因此您可以添加typedef

struct Foo { ... };
typedef struct Foo Foo;

现在struct Foo(在标记名称空间中)和仅普通的 Foo(在普通标识符名称空间中)都引用相同的内容,并且您可以自由地声明Foo没有struct关键字的类型的对象。

构造:

typedef struct Foo { ... } Foo;

最后,

typedef struct { ... } Foo;

声明一个匿名结构并typedef为其创建一个。因此,使用此构造,它在标签名称空间中没有名称,而在typedef名称空间中只有名称。这意味着它也不能被预先声明。 如果要进行前向声明,则必须在标签命名空间中为其命名


在C ++中,所有structunionenumclass声明像他们是隐式typedef“版,只要名称不与另一个同名的声明所隐藏。有关完整的详细信息,请参见Michael Burr的答案

发布了119 篇原创文章 · 获赞 152 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/weixin_40539125/article/details/102596878
今日推荐