C++ union/struct使用小结

1.在C++中,struct与class唯一的区别:

In C++,  the only difference between a class and a struct is that members and base classes are private by default in classes,  whereas they are public by default in structs.

2. 匿名struct

typedef struct{
    int x;
    foo(){};
} foo;

上面的声明将无法通过编译,定义了一个匿名struct并取foo为它的别名,匿名struct无法自定义构造函数。可修改为

typedef struct foo{
int x;
foo(){};
} foo;

3. struct的显式初始化

C++ Primer第4版12.4.5:
对于没有定义构造函数并且其全体数据成员均为public的类,可以采用与初始化数组元素相同的方式初始化其成员:
struct Data
{    
    int ival;
    int ival2;
};

Data d ={0, 0};

 union也可以用显式初始化,但是只能为第一个成员提供初始化式,该初始化式必须括在一对花括号中。

4. 使用struct声明类型和定义变量

struct A
{    
    int a;    
    ​int b;
};

上面的代码定义了结构体A,从而可以使用A声明变量,如A a;

struct A
{    
    ​int a;    
    int b;
}a;

上面的代码在定义了结构体A的同时,还声明了类型为A变量a;若将A注释掉则声明了一个匿名struct类型的变量a;

struct
{
    union //_union
    {
        struct Reg
        {
            int a;
            int b;
        }Register;
        struct Cmd
        {
            int a;
            int b;
        }Command;
   };
 }dat;

上面的代码则声明了一个匿名struct类型的变量dat,内部的两个变量Register和Command共用union的空间;

若把union后面的_union加上,则表示声明了一个union类型,dat中将无实际数据变量。

posted on 2015-06-01 12:53  adanus  阅读(1138)  评论(0编辑  收藏  举报

导航