首页 > 编程语言 > 详细

【C++】共用体\联合体(union)

时间:2019-11-16 16:47:55      阅读:99      评论:0      收藏:0      [点我收藏+]

          共用体的用法与结构体差不多,只不过将关键字由struct变成了union。共用体使不同的类型变量存放到同一段内存单元中,所以共用体在同一时刻只能存储一个数据成员的值,共用体的大小等于最大成员的大小(结构体变量的大小是所有数据成员大小的总和)。

         在程序中改变共用体的一个成员,其他成员也会随之改变。不是强制类型转换!而是因为他们的值的每一个二进制位都被新值所覆盖。

 1 #include <iostream>
 2 #include <string>
 3 #include <stdio.h>
 4 using namespace std;
 5 union DateUnion
 6 {
 7     int iInt1;
 8     int iInt2;
 9     double douDou;
10     char cChar;
11 };
12 int main()
13 {
14     DateUnion A;
15     A.iInt1 = 97;
16     cout << "A.iInt1=" << A.iInt1 << endl;
17     cout << "A.iInt2=" << A.iInt2 << endl;
18     cout << "A.douDou=" << A.douDou << endl;
19     cout << "A.cChar=" << A.cChar << endl << endl;
20 
21     A.iInt2 = 65;
22     cout << "A.iInt1=" << A.iInt1 << endl;
23     cout << "A.iInt2=" << A.iInt2 << endl;
24     cout << "A.douDou=" << A.douDou << endl;
25     cout << "A.cChar=" << A.cChar << endl << endl;
26 
27     A.cChar = a;
28     cout << "A.iInt1=" << A.iInt1 << endl;
29     cout << "A.iInt2=" << A.iInt2 << endl;
30     cout << "A.douDou=" << A.douDou << endl;
31     cout << "A.cChar=" << A.cChar << endl << endl;
32     system("pause");
33     return 0;
34 }

运算结果:

技术分享图片


注意:

string可以作为结构体的成员但是不能作为共用体的成员。所以下面共用体的定义是错误的:

union DateUnion
{
    int iInt1;
    int iInt2;
    double douDou;
string strChar; };

严重性 代码 说明 项目 文件 行 禁止显示状态

错误 C2280 “DateUnion::DateUnion(void)”: 尝试引用已删除的函数 

技术分享图片

此错误的原因:String 是一个类,有自己的构造函数,析构函数。

我们分析一下:

Union的一大特征在于,一个Union类中的所有数据共享同一段内存。如果union类的成员包含自己的构造函数,析构函数,那么同一Union类的成员在初始化时,就有可能会执行不同的构造函数。这是无法预料的。所以,我们在定义Union类时要尽量避免成员变量是对象(含有自己的构造函数)。

解决方案:String 换成基本的数据类型:char 等

union DateUnion
{
    int iInt1;
    int iInt2;
    double douDou;
    char cChar;
};

 

 

【C++】共用体\联合体(union)

原文:https://www.cnblogs.com/KMould/p/11872019.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!