C++中'struct'和'typedef struct'的区别?

2022-01-30 00:00:00 struct c++ typedef

在C++中,有什么区别:

struct Foo { ... };

和:

typedef struct { ... } Foo;

推荐答案

在 C++ 中,只有细微的差别.它是从 C 中继承下来的,在这方面有所作为.

In C++, there is only a subtle difference. It's a holdover from C, in which it makes a difference.

C 语言标准(C89 §3.1.2.3,C99 §6.2.3 和 C11 §6.2.3) 为不同类别的标识符规定了单独的命名空间,包括 标签标识符(用于struct/union/enum)和普通标识符(用于typedef 和其他标识符).

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).

如果你刚才说:

struct Foo { ... };
Foo x;

你会得到一个编译器错误,因为 Foo 只在标签命名空间中定义.

you would get a compiler error, because Foo is only defined in the tag namespace.

您必须将其声明为:

struct Foo x;

任何时候你想引用一个Foo,你总是不得不称它为一个struct Foo.这很快就会变得烦人,因此您可以添加 typedef:

Any time you want to refer to a Foo, you'd always have to call it a struct Foo. This gets annoying fast, so you can add a typedef:

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

现在struct Foo(在标签命名空间中)和普通的Foo(在普通标识符命名空间中)都指的是同一个东西,你可以自由地声明对象Foo 类型,不带 struct 关键字.

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.

构造:

typedef struct Foo { ... } Foo;

只是声明和typedef的缩写.

最后,

typedef struct { ... } Foo;

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

declares an anonymous structure and creates a typedef for it. Thus, with this construct, it doesn't have a name in the tag namespace, only a name in the typedef namespace. 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.

在 C++ 中,所有 struct/union/enum/class 声明的行为就像它们是隐含的 typedef 的,只要该名称没有被另一个同名的声明隐藏.有关完整详细信息,请参阅 Michael Burr 的回答.

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. See Michael Burr's answer for the full details.

相关文章