Difference between 'struct' and 'typedef struct' in C++?
2016-06-20 15:19
507 查看
原址
1. In C, there are two different namespaces of types: a namespace of
and a namespace of
If you just said:
You would get a compiler error, because
only defined in the tag namespace. You'd have to declare it as:
2. Any time you want to refer to a
you'd always have to call it a
Now both
the typedef namespace) both refer to the same thing,
3. and you can freely declare objects of type
the struct keyword. The construct
is just an abbreviation for the declaration and
4. Finally,
declares an anonymous structure and creates a
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.(注:匿名的结构体定义也无法自定义各种构造函数)
5. In C++, all
declarations act like they are implicitly
as long as the name is not hidden by another declaration with the same name. See Michael
Burr's answer for the full details.
摘抄:
In C++, there is only a subtle difference. It's a holdover from C, in which it makes a difference.1. In C, there are two different namespaces of types: a namespace of
struct/
union/
enumtag names
and a namespace of
typedefnames.
If you just said:
struct Foo { ... }; Foo x;
You would get a compiler error, because
Foois
only defined in the tag namespace. You'd have to declare it as:
struct Foo x;
2. 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;
Now both
struct Foo(in the tag namespace) and just plain
Foo(in
the typedef namespace) both refer to the same thing,
3. and you can freely declare objects of type
Foowithout
the struct keyword. The construct
typedef struct Foo { ... } Foo;
is just an abbreviation for the declaration and
typedef.
4. Finally,
typedef struct { ... } Foo;
declares an anonymous structure and creates a
typedeffor
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.(注:匿名的结构体定义也无法自定义各种构造函数)
5. 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++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性