[英]struct and typedef
The second option cannot reference itself. 第二个选项无法引用自身。 For example: 例如:
// Works:
struct LinkedListNode_ {
void *value;
struct LinkedListNode_ *next;
};
// Does not work:
typedef struct {
void *value;
LinkedListNode *next;
} LinkedListNode;
// Also Works:
typedef struct LinkedListNode_ {
void *value;
struct LinkedListNode_ *next;
} LinkedListNode;
No, they're not exactly equivalent. 不,他们并不完全等同。
In the first version Foo
is a typedef for the named struct myStruct
. 在第一个版本中, Foo
是命名struct myStruct
的typedef。
In the second version, Foo
is a typedef
for an unnamed struct
. 在第二个版本中, Foo
是未命名struct
的typedef
。
Although both Foo
can be used in the same way in many instances there are important differences. 尽管在许多情况下Foo
都可以以相同的方式使用,但是存在重要的差异。 In particular, the second version doesn't allow the use of a forward declaration to declare Foo
and the struct
it is a typedef
for whereas the first would. 特别是,第二个版本不允许使用前向声明来声明Foo
,而struct
它是一个typedef
,而第一个版本则是。
The first form allows you to refer to the struct before the type definition is complete, so you can refer to the struct within itself or have mutually dependent types: 第一种形式允许您在类型定义完成之前引用结构,因此您可以在其自身内引用结构或具有相互依赖的类型:
struct node {
int value;
struct node *left;
struct node *right;
};
typedef struct node Tree;
or 要么
struct A;
struct B;
struct A {
struct B *b;
};
struct B {
struct A *a;
};
typedef struct A AType;
typedef struct B Btype;
You can combine the two like so: 您可以将两者结合起来:
typedef struct node {
int value;
struct node *left;
struct node *right;
} Tree;
typedef struct A AType; // You can create a typedef
typedef struct B BType; // for an incomplete type
struct A {
BType *b;
};
struct B {
AType *a;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.