C++基础(4.4-4.5)——struct&union

struct & union

/* 定义 */
struct StructName {
    
    
	int attribute_1;
	char attribute_2[20];
	double attribute_3;
};

/* 声明 */
struct StructName s1;
StructName s2;	/* C++允许在声明结构变量时省略关键struct  */

/* 初始化 */
struct StructName {
    
    1, "hello", 1.1};
struct StructName={
    
    1, "hello", 1.1}; /* 等号是可选的 */
struct StructName {
    
    }; /* 如大括号内未包含任何东西,attribute_1、attribute_3都被设置为零,且attribute_2每个字节被设置为零 */
/* 最后, 不允许缩窄转换 */

/* 赋值 */
/* 可以直接使用(=)将struct赋值给另一个同类型struct, 
这样结构中的成员都将被设置为另一个结构中相应成员的值, 
即使成员是数组,这种赋值被称为成员赋值(memberwise assignment) */
struct Me {
    
    
	char name[20];
	int age;
} s1 {
    
    
	"JianRong"
	26
};

struct Me s2 = s1;
cout << s2.name << "\t" << s2.age << endl; /* JianRong 26*/

/* 结构数组 */
Me me[100];	/* create one hundred me ^-^*/
cin >> me[0].name; 
cout << me[0].name << endl;

Me mes[100] = {
    
    
	{
    
    "JianRong", 26},
	{
    
    "JianRong", 26}
};
cout << mes[0].name << endl;
cout << mes[1].age << endl;

/* 结构中的位字段 */
/* 与C语言相同,C++也允许指定占用特定位数的结构成员,这使得创建与某个硬件
设备上的寄存器对应的数据结构非常方便。
 */
 struct torgle_register 
 {
    
    
 	unsigned int SN : 4;	// 4 bits for SN value
 	unsigned int : 4; 		// 4 bits unused
 	bool goodIn	: 1;		// valid input (1 bit)
 	bool goodTorgle : 1; 	// successful torgling
 };
 /* 可以像通常那样初始化字段, 也可以使用标准的结构表示法来访问位字段 */
 torgle_register tr = {
    
    14, true, false};
 
 /* 位字段通常用在低级编程中,一般来说,可以使用整形和按位运算符代替这种操作 */

union

/*共用体(union)是一种数据格式,它能够存储不同的数据类型,但只能同时存储一种一种 */
union one4all 
{
    
    
	int int_val;
	long long_val;
	double double_val;
};
/* 可以使用one4all变量存储int、long或double,但是要在不同时间运行
而由于共用体每次只能存储一个值,因此它须有足够的空间存储最大的成员,所以
共用体的长度为其最大成员的长度 */
one4ll pail;
pail.int_val = 15;		// strore an int
pail.double_val = 1.38; // store a double, int value is lost

/* 匿名共用体 */
/* 匿名共用体(anonymous union)没有名称,其成员将成为位于相同地址处的变量, 但相同时间只能有一个成员为当前成员 */
struct widget 
{
    
    
	char brand[20];
	int type;
	union	// anonymous union
	{
    
    
		long id_num;		// type 1 widgets
		char id_char[20];	// other widgets
	}
};

...
widget prize;
...
if (prize.type = 1)
	cin >> prize.id_num;
else
	cin >> prize.id_char;
/* 共用体长用于节省内存,也常用于操作系统数据结构或硬件数据结构 */

猜你喜欢

转载自blog.csdn.net/gripex/article/details/105143664