C的union的应用
来源:互联网 发布:阿里云二手域名 编辑:程序博客网 时间:2024/05/21 18:32
1. 概念
union是一种特殊的类(struct/class),其特殊之处在于,union内的变量共享一段内存,并且union占用内存大小等于其内占用内存最大的变量的大小
eg:
//定义结构struct Node_s{double a;int b;};//定义unionunion Node_u{double a;int b;};//输出sizecout << "size of struct:" << sizeof(Node_s) << endl;cout << "size of union:" << sizeof(Node_u) << endl;
输出(vs2010, 32位系统):
size of struct:16
size of union:8
2. 应用
union最大的用处在于在某些场景下用来节省内存。
我们常见的一个场景是,有两个变量,但这两个变量我们不会同时需要。
例如,一个人的属性是:姓名、工作类型、工作描述,在描述工作的时候,针对不同的职业,有不同的属性,但是,一个人不会同时拥有两个职业(一般情况下)
code如下:
//工程师struct Engineer {int type; //方向char company[1024];};//教师struct Teacher {int title; // 叫兽,副叫兽?int type; //所在专业char school[1024]; //学校名称};//人struct Person{char name[128]; //姓名int job_type; //engineer or teacherunion Work{Engineer engineer;Teacher teacher;}work;};//输出sizecout << "size of Engineer:" << sizeof(Engineer) << endl;cout << "size of Teacher:" << sizeof(Teacher) << endl;cout << "size of Person:" << sizeof(Person) << endl;
输出:
size of Engineer:1028
size of Teacher:1032
size of Person:1164
eg:
//工程师struct Engineer {int type; //方向char company[1024];};//教师struct Teacher {int title; // 叫兽,副叫兽?int type; //所在专业char school[1024]; //学校名称};//人struct Person{char name[128]; //姓名int job_type; //engineer or teacherunion{Engineer engineer;Teacher teacher;};};//匿名对象直接使用Person person;person.engineer.type = 100;//输出sizecout << "size of Engineer:" << sizeof(Engineer) << endl;cout << "size of Teacher:" << sizeof(Teacher) << endl;cout << "size of Person:" << sizeof(Person) << endl;
3. 使用注意
如果类是union的成员,则成员类不能提供构造函数、析构函数。这是因为union的成员共享内存,编译器无法保证这些成员在构造时不被破坏,也无法保证离开时调用析够函数。
eg:
//定义结构struct Node_s{Node_s(){}double a;int b;};//定义unionunion Node_u{Node_s n_s;double a;int b;};
编译将报错:error C2620: 成员“wmain::Node_u::n_s”(属于联合“wmain::Node_u”)具有用户定义的构造函数或不常用的默认构
但是,如果成员类不提供构造函数,则OK
eg:
//定义结构struct Node_s{double a;int b;};//定义unionunion Node_u{Node_s n_s;double a;int b;};//输出sizecout << "size of struct:" << sizeof(Node_s) << endl;cout << "size of union:" << sizeof(Node_u) << endl;
输出:
size of struct:16
size of union:16
4. 参考
http://blog.chinaunix.net/space.php?uid=14121858&do=blog&cuid=449785
http://hi.baidu.com/hsyl/blog/item/3a9af91900a43376dbb4bdf0.html/cmtid/94dc8b82ebba7a9ff703a6f2
原文地址:http://blog.csdn.net/yfkiss/article/details/6674348
0 0
- C的union的应用
- union的应用
- C++Union的用法
- C++Union的用法
- SQL SELECT UNION的应用
- C中union的用法
- c/c++ union的用法
- c/c++语言的union
- C语言union的用法
- C语言Union的使用
- C的struct, union, enum
- union(C/C++)使用的一些总结
- [Union]C语言编程中联合Union的学习
- C语言联合体(union)的使用方法及其本质-union
- C++中union的应用剖析
- C++中union的应用剖析
- C++中union的应用剖析
- c++中union的应用剖析
- Linux常用命令(十六) - whereis
- 线性表实验相关程序代码
- 基于PageRank的社交网络用户影响力
- sDBVGfhfdh
- “黑暗潜伏者” -- 手机病毒新型攻击方式
- C的union的应用
- C/C++枚举注册表某项下的所有子项【代码示例】
- 系统测试
- 在线框架引用|bootstrap|jq|jqmobile|CSS框架
- Android应用程序中获取view的位置
- Photoshop脚本 > 使用ExtendScript编写Ps脚本
- ThreadLocal小记
- Android 4.4 沉浸式透明状态栏与导航栏
- 找不到python33_d.lib的链接错误