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

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

问题描述

在C ++中,是否有任何区别:

In C++, is there any difference between:

struct Foo { ... };

typedef struct { ... } Foo;


推荐答案

在C ++中,

在C中,有两种不同的命名空间类型: struct / union / 枚举 code> typedef 名称。如果你刚才说:

In C, there are two different namespaces of types: a namespace of struct/union/enum tag names and a namespace of typedef names. If you just said:

struct Foo { ... };
Foo x;

你会得到一个编译错误,因为 Foo 只在标签命名空间中定义。您必须声明为:

You would get a compiler error, because Foo is only defined in the tag namespace. You'd have to declare it as:

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 (在typedef命名空间)都指向相同的事情,你可以自由地声明类型 Foo 无struct关键字。构造:

Now both struct Foo (in the tag namespace) and just plain Foo (in the typedef namespace) both refer to the same thing, and you can freely declare objects of type Foo without the struct keyword. The construct:

typedef struct Foo { ... } Foo;

只是声明的缩写, typedef 。最后,

is just an abbreviation for the declaration and typedef. Finally,

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 can't 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 /类声明的行为就像隐式 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天全站免登陆