目录
一、结构体
1.结构体struct
把几个不同类型的成员打包在一起,形成新的数据类型
struct Student{
char name[4];
int born;
bool male;
};
struct Student stu;//C语言
Student stu;//C++
strcpy(stu.name, "Yu");用.操作成员变量
stu.born = 2000;
stu.male = true;
struct Student stu = {"Yu", 2000, true};//初始化
struct Student students[100];//结构体数组,里面有100个结构体
students[50].born = 2002;
| ||
| 13 | |
| 12 | |
| 11 | |
| 10 | |
| 9 | |
male | 1 | 8 |
born | 2000 | 7 |
6 | ||
5 | ||
4 | ||
name | 0 | 3 |
0 | 2 | |
'u' | 1 | |
'Y' | 0 | |
| -1 | |
| -2 | |
|
2. 结构体成员对齐
struct Student1{
int id;
bool male;
char label;
float height;
};
| ||
| ||
height |
| 11 |
10 | ||
9 | ||
8 | ||
| 7 | |
| 6 | |
label |
| 5 |
male |
| 4 |
id |
| 3 |
2 | ||
1 | ||
0 | ||
| ||
| ||
为了io方便把变量对齐,绝对0地址,都是4的倍数,8的倍数height到6,一次性就装不完,装两次,后面读写效率更高
struct Student2{
int id;
bool male;
float height;
char label;
};
| ||
| ||
| 15 | |
| 14 | |
| 13 | |
label |
| 12 |
weight |
| 11 |
10 | ||
9 | ||
8 | ||
| 7 | |
| 6 | |
| 5 | |
male |
| 4 |
id |
| 3 |
2 | ||
1 | ||
0 | ||
| ||
|
一般4个字节对齐
二、联合体
一个IP地址
union ipv4address{
std::uint32_t address32;
std::uint8_t address8[4];
};
联合体里面所有成员共享同一个内存
两个变量首地址相同,以最大的成员变量为准
sizeof(union ipv4address) is 4.
Union | Address | ||
| |||
|
| p+4 | |
address8[3] | address32 | 127 | p+3 |
address8[2] | 0 | p+2 | |
address8[1] | 0 | p+1 | |
address8[0] | 1 | p+0 | |
| p-1 | ||
|
三、枚举
替换const
enum color {WHITE, BLACK, RED, GREEN, BLUE, YELLOW, NUM_COLORS};
enum color pen_color = RED;
pen_color = color(3);
cout << "We have " << NUM_COLORS << " pens." << endl;
pen_color += 1; //error!枚举类型不可做算数运算
int color_index = pen_color;
color_index += 1;
cout << "color_index = " << color_index << endl;
四、综合运用(L1范数为例)
L1范数
enum datatype {TYPE_INT8=1, TYPE_INT16=2, TYPE_INT32=4, TYPE_INT64=8};
//point用来表示3维世界的向量(x,y,z),向量用union表示,向量的数据类型可能不同,该用那个由枚举类型决定
struct Point{
enum datatype type;
union {
std::int8_t data8[3];
std::int16_t data16[3];
std::int32_t data32[3];
std::int64_t data64[3];
};
};
size_t datawidth(struct Point pt)
{
return size_t(pt.type) * 3;
}
int64_t l1norm(struct Point pt)//L1范数
{
int64_t result = 0;
switch(pt.type)
{
case (TYPE_INT8):
result = abs(pt.data8[0]) +
abs(pt.data8[1]) +
abs(pt.data8[2]);
break;
...
五、typedef
使用 typedef 为现有类型创建别名
typedef int myint;
typedef unsigned char vec3b[3];
typedef struct _rgb_struct{//name _rgb_struct can be omit
unsigned char r;
unsigned char g;
unsigned char b;
} rgb_struct;
myint num = 32;
unsigned char color[3];
vec3b color = {255, 0, 255}; //color是个数组,和上面一样
rgb_struct rgb = {0, 255, 128};
常用在系统头文件
_uint8_t.h
#ifndef _UINT8_T
#define _UINT8_T
typedef unsigned char uint8_t;
#endif /* _UINT8_T */