1、结构
struct test
相当于class test
,唯一的不同之处在于如果不设置访问控制struct默认为public
,而class默认为private
。
2、联合
union默认的访问控制为public
#include<stdio.h>
union test1
{
int z;
struct test2
{
char x;
char y;
}test2;
}test1;
int main()
{
test1.z=0x1234;
printf("x=%x\n",test1.test2.x);
printf("y=%x\n",test1.test2.y);
printf("y=%x\n",test1.z);
}
/*result:
x=34
y=12
z=1234
*/
为什么显示的结果为x=34;y=12;z=1234;
?联合成员共同享用一个内存位置,赋值时把0x1234填入了该初始地址,长度为两个字节。char变量的大小只有一个字节,所以x只能保存0x1234的低两位,y只能存放0x1234的高两位,结果以十六进制显示出来。
3、位段
struct test
{
unsigned int f1:1;//f1占一个二进制位
unsigned int f2:3;//f2占三个二进制位
}