C++ 中“struct"和“typedef struct"的区别? [英] Difference between 'struct' and 'typedef struct' in C++?

查看:42
本文介绍了C++ 中“struct"和“typedef struct"的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.3C11 §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'ed,只要名称没有被另一个同名的声明隐藏.请参阅 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.

这篇关于C++ 中“struct"和“typedef struct"的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆