C++ union enum 探究

本文探讨了在C++面向对象编程中,UNION与enum的区别及应用场景,特别是UNION如何在内存管理中发挥作用,以及在解决内存资源有限情况下的优势与使用注意事项。

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

这两个关键字并不怎么常用,但是看C++primer plus 面向对象编程部分的时候总是能看到类中有用enum定义的变量。所以想弄清楚这两个关键词到底有什么用。

首先是UNION,MSDN上的解释

union is a user-defined type in which all members share the same memory location.

 This means that at any given time a union can contain no more than one object from its list of members.

It also means that no matter how many members a union has, it always uses only enough memory to store the largest member.

Unions can be useful for conserving memory when you have lots of objects and/or limited memory.

However they require extra care to use correctly because you are responsible for ensuring that you always access the last member that was written to.

If any member types have a non-trivial constructor, then you must write additional code to explicitly construct and destroy that member.

Before using a union, consider whether the problem you are trying to solve could be better expressed by using a base class and derived classes.


可以看到test1.a的值已经丢失了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值