Chinaunix首页 | 论坛 | 博客
  • 博客访问: 144260
  • 博文数量: 34
  • 博客积分: 1557
  • 博客等级: 上尉
  • 技术积分: 245
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-22 19:30
文章分类

全部博文(34)

文章存档

2017年(1)

2016年(1)

2015年(4)

2014年(2)

2011年(8)

2010年(6)

2009年(12)

我的朋友

分类: C/C++

2011-03-24 11:25:18

在看侯捷STL书中,看到
union obj
{
  union obj *free_list_link;
  char client_data[1];
 }; 时,对UNION在书中的作用不是很理解,才翻出来找找关于UNION 的信息。
C++中的union,很大程度上是为了兼容C语言才提出来的,看了下面的文章,你就会感觉到,C++中的union显得有些不伦不类。如果需要用到union,我们最好使用传统的union,也就是C中的union。至于下面提到的C++中的union独有的特点,在实际工作中,最好不要用;当然,了解一下还是有好处的,至少和朋友吹牛的时候可以用到,^_^ 

在C++中,union有以下特点: 
1.   union可以定义自己的函数,包括   constructor   以及   destructor。 
2.   union支持   public   ,   protected   以及   private   权限。 
读者看到这可能会问,要是这样的话,union与class还有什么区别吗?区别当然还是有的 
3.   union不支持继承。也就是说,union既不能有父类,也不能作为别人的父类。 
4.   union中不能定义虚函数。 
5.   不是所有类型的变量都能作为union的成员变量。POD(注1)类型可以作为union的成员变量。如果一个类,包括其父类,含有自定义的constructor,copy   constructor,destructor,copy   assignment   operator,   virtual   function中的任意一个,那么这种类型的变量不能作为union的成员变量(注3)。 
6.   union中可以定义static以及引用类型的成员变量,不过C++标准不推荐这样做,包含这样代码的程序是ill-formed的 

如果我们在定义union的时候没有定义名字,那么这个union被称为匿名union(anonymous   union)。匿名union的特点如下: 

1.   匿名union中不能定义static变量。 
2.   匿名union中不能定义函数。 
3.   匿名union中不支持   protected   以及   private   权限。 
4.   在全局域以及namespace中定义的匿名union只能是static的。 

ok,写道最后,留一个问题给大家: 
union   {   
      int   aa;   
      char*   p;   
}obj; 
这里定义的union是不是匿名的union?   

注1:  POD   的全称是   Plain   Old   Data,在C++标准中,POD是这样定义的: 
Arithmetic   types   (3.9.1),   enumeration   types,   pointer   types,   and   pointer   to   member   types   (3.9.2),   and   cv-qualified(注2)   versions   of   these   types   (3.9.3)   are   collectively   called   scalar   types.   Scalar   types,   POD-struct   types,POD-union   types   (clause   9),   arrays   of   such   types   and   cv-qualified   versions   of   these   types   (3.9.3)   are   collectively   called   POD   types. 
我们可以这样理解POD,与C兼容的数据类型可以被成为POD类型。 

注2:什么是cv-qualified   ? 
这里的CV分别是const   以及volatile的缩写。用const,volatile以及const   volatile之一作修饰的变量被成为cv-qualified   ,否则该变量是cv-unqualified   

注3:class是不是POD类型? 
我觉得class不应算作POD类型,但是如果一个class没有non-trivial   的   constructor,   destructor,   以及   copy   assignmet   operator这些东西的话,这个class事实上已经退化成一个POD类型了,就相当于C中的struct。这样,union中就可以包含你这样的数据类型。
阅读(1982) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~