共用体union
概述
- 结构体struct可以同时存储int、long、double等不同类型,
而共用体union只能存储int、long、double等不同类型中的一个。
- 共用体union比struct节省内存,常用于配置低的硬件,如控制烤箱、MP3播放器或火星漫步者等嵌入式編程。
基本语法
union one4all { int int_val; long long_val; double double_val; }; |
共用体每次只能存储一个值,因此它必须有足够的空间来存储最大的成员。
所以,共用体的长度为最大成员长度。
匿名共用体
struct widget { char brand[20]; int type;
union { long id_num; char id_char[20]; };
}; |
由于共用体是匿名的,因此id_num和id_char被视为prize的两个成员,它们的地址相同,所以不需要中间标识符。我们只需要负责确定当前哪个成员是活动的。
改进
共用体union中只能储存静态数据类型(基本数据类型或者没有构造函数、析构函数的类/结构体)。
可以使用不定参数的模板类写一个Union,来改进union的不足。
//二元智能共用体:union的升级版 //使用指针指向动态类型,频繁地申请空间会使得效率变低。 //此外,若频繁地覆盖Union,动态类型的构造函数和析构函数也会拖低效率。 template<typename first, typename second> class Union { public: first* _first; second* _second; public: Union() :_first(nullptr), _second(nullptr) {} Union(first*& _first) :_first(_first), _second(nullptr) {} Union(second*& _second) :_first(nullptr), _second(_second) {} ~Union();
void set(const first& _first); void set(const second& _second);
bool have(const first&); bool have(const second&);
first& operator=(const first& _first); second& operator=(const second& _second);
template<typename __first, typename __second> friend std::ostream& operator<<(std::ostream& os, const Union<__first, __second>& _union);
template<typename __first, typename __second> friend String& operator<<(String& str, const Union<__first, __second>& _union); }; |

浙公网安备 33010602011771号