C++ union(只支持基础类型)

本文探讨了C++标准中关于union使用的基本类型限制,并介绍了如何使用boost::variant替代。此外,还提到了C++0x标准引入的Unrestricted Unions特性,允许在union中存放非POD类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

遇到一个union里面放一些非基本类型编译不通过的问题,查了一下得到如下解释


Current C++ standard does not allow non-POD types inside unions. Hence you get this compiler error from gcc.
Instead of using C unions, you should use boost::variant. Check the doccumentationhere.

To add to the above:
The new C++ standard(C++0x) adds a new feature called as Unrestricted Unions, which supports storing non-POD types to a Union.




如下代码编译不通过

typedef complex<float> complexF;

struct AAA{
    AAA{
    AAA{ complexF& tzsr0,
                const complexF& tzsr1,
                const complexF& tzsr2,
                const complexF& tzsr3):zsr0(tzsr0), zsr1(tzsr1),zsr2(tzsr2), zsr3(tzsr3){};

    // union not support type with construct
   union{
        struct{
            complexF  zsr0;
            complexF  zsr1;
            complexF  zsr2;
            complexF  zsr3;
        };
        complexF   zzz[4];
     };

};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值