C++ 联合体Union学习

时间:2021-06-06 22:34:41   收藏:0   阅读:24

https://www.cnblogs.com/fengty90/p/3768840.html

1.Union

当多个数据需要共享内存或者多个数据每次只取其一时,可以利用联合体(union)。

#include<iostream>
using namespace std;

union U1
{
    int n;
    char s[11];
    double d;
};
union U2
{
    int n;
    char s[5];
    double d;
};
int main()
{
    U1 u1;
    U2 u2;
    cout<<sizeof(u1)<<\t<<sizeof(u2)<<endl;
    cout<<"u1各数据地址:\n"<<&u1<<\t<<&u1.d<<\t<<&u1.s<<\t<<&u1.n<<endl;
    cout<<"u2各数据地址:\n"<<&u2<<\t<<&u2.d<<\t<<&u2.s<<\t<<&u2.n<<endl;
}

输出:

16    8
u1各数据地址:
0x74fe10    0x74fe10    0x74fe10    0x74fe10
u2各数据地址:
0x74fe08    0x74fe08    0x74fe08    0x74fe08

可以发现u1和u2对象的地址,就是首个元素的地址,并且所有元素的地址都相同!

SGI STL的二级空间配置器的free list用到了它。

https://www.cnblogs.com/fengty90/p/3768840.html

原文:https://www.cnblogs.com/BlueBlueSea/p/14856430.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!