In C++, there is only a subtle difference.
(在C ++中,只有一个微妙的区别。)
It's a holdover from C, in which it makes a difference. (这是C的延续,它有所作为。)
The C language standard ( C89 §3.1.2.3 , C99 §6.2.3 , and C11 §6.2.3 ) mandates separate namespaces for different categories of identifiers, including tag identifiers (for struct
/ union
/ enum
) and ordinary identifiers (for typedef
and other identifiers).
(C语言标准( C89§3.1.2.3 , C99§6.2.3和C11§6.2.3 )要求为不同类别的标识符分别命名空间,包括标记标识符 (用于struct
/ union
/ enum
)和普通标识符 (用于typedef
和其他标识符)。)
If you just said:
(如果你刚才说:)
struct Foo { ... };
Foo x;
you would get a compiler error, because Foo
is only defined in the tag namespace.
(您会收到编译器错误,因为Foo
仅在标记名称空间中定义。)
You'd have to declare it as:
(您必须将其声明为:)
struct Foo x;
Any time you want to refer to a Foo
, you'd always have to call it a struct Foo
.
(每当你想要引用Foo
,你总是要把它称为struct Foo
。)
This gets annoying fast, so you can add a typedef
: (这会很快烦人,所以你可以添加一个typedef
:)
struct Foo { ... };
typedef struct Foo Foo;
Now struct Foo
(in the tag namespace) and just plain Foo
(in the ordinary identifier namespace) both refer to the same thing, and you can freely declare objects of type Foo
without the struct
keyword.
(现在struct Foo
(在标记命名空间中)和普通Foo
(在普通标识符命名空间中)都引用相同的东西,并且您可以在没有struct
关键字的情况下自由声明Foo
类型的对象。)
The construct:
(构造:)
typedef struct Foo { ... } Foo;
is just an abbreviation for the declaration and typedef
.
(只是声明和typedef
的缩写。)
Finally,
(最后,)
typedef struct { ... } Foo;
declares an anonymous structure and creates a typedef
for it.
(声明一个匿名结构并为其创建一个typedef
。)
Thus, with this construct, it doesn't have a name in the tag namespace, only a name in the typedef namespace. (因此,使用此构造,它在标记名称空间中没有名称,只有typedef名称空间中的名称。)
This means it also cannot be forward-declared. (这意味着它也无法向前宣布。)
If you want to make a forward declaration, you have to give it a name in the tag namespace . (如果要进行前向声明,则必须在标记名称空间中为其指定名称 。)
In C++, all struct
/ union
/ enum
/ class
declarations act like they are implicitly typedef
'ed, as long as the name is not hidden by another declaration with the same name.
(在C ++中,所有struct
/ union
/ enum
/ class
声明都像隐式typedef
一样,只要该名称不被另一个具有相同名称的声明隐藏。)
See Michael Burr's answer for the full details. (有关详细信息,请参阅Michael Burr的答案 。)