结构体
结构体是一个由程序员定义的数据类型,可以容纳许多不同的数据值
- 结构体中可以有什么
(1) 各种数据类型、数组、指针(包括this指针)等
(2) 函数 - 结构体声明
结构体声明的格式是struct StructName {内容};
struct men {
int age;
int height,weight;
men(int a, int h, int w) {
age = a;
height = h;
weight = w;
}
void fight() {
cout << "Fighting!!!" << endl;
}
void show() {
cout << "my age is " << age << endl;
cout << "my height is " << height << endl;
cout << "my weight is " << weight << endl;
}
};
- C++结构体和类的异同
相同之处
(1) 结构体中可以包含函数,也可以定义public、private、protected数据成员
(2) 结构体中可以继承和被继承
struct men {
public:
int age;
int height,weight;
men(int a, int h, int w) {
age = a;
height = h;
weight = w;
}
void fight() {
cout << "Fighting!!!" << endl;
}
void show() {
cout << "my age is " << age << endl;
cout << "my height is " << height << endl;
cout << "my weight is " << weight << endl;
}
};
struct student:men {
int grade;
student(int a,int h,int w,int g):men(a,h,w) {
grade = g;
}
};
- 结构体初始化
(1) 赋值初始化
赋值初始化有两种情况,第一种是完全赋值,如下所示
struct bird {
int weight;
int type;
int age;
void show() {
cout << "this bird's weight is " << weight << endl;
cout << "this bird's type is " << type << endl;
cout << "this bird's age is " << age << endl;
}
};
int main() {
bird mybird = {1,2,3};
mybird.show();
return 0;
}
第二种是部分赋值,如下所示
struct bird {
int weight;
int type;
int age;
void show() {
cout << "this bird's weight is " << weight << endl;
cout << "this bird's type is " << type << endl;
cout << "this bird's age is " << age << endl;
}
};
int main() {
bird mybird = {1,2};
mybird.show();
return 0;
}
要注意的是部分赋值是按顺序赋值的,上面代码只给weight和age赋值,age没有被赋值。
(2) 构造函数初始化
可以看到,赋值初始化虽然简单易操作,但是不太灵活,使用构造函数可以很灵活地来初始化结构体
struct men {
public:
int age;
int height,weight;
men(int a, int h, int w) {
age = a;
height = h;
weight = w;
}
void fight() {
cout << "Fighting!!!" << endl;
}
void show() {
cout << "my age is " << age << endl;
cout << "my height is " << height << endl;
cout << "my weight is " << weight << endl;
}
};
int main() {
men qzq(1,2,3);
return 0;
}
- 结构体使用
如何使用结构体?答案是就那么使用,看上面的例子就知道了,不多说。
联合体
利用union可以用相同的存储空间存储不同型别的数据类型,从而节省内存空间。用联合体可以很方便地将4个字节的int类型拆分成四个字节,这在用串口发送数据的时候很方便。
union DataType {
int n;
char s[12];
double d;
};
int main() {
DataType data;
data.n = 10;
printf("%x %x %x %x\n",data.s[0], data.s[1], data.s[2], data.s[3]);
return 0;
}
联合体中的所有数据的基址都一样。
枚举类型
枚举类型是C++的一种派生数据类型,它是由用户定义的若干枚举常量的集合,通过字符的描述来增加程序的可读性。枚举的元素本质是int类型。
定义方法enum 类型名{常量列表}
enum food {
meat, rice, fruit
};
其中meat为0,rice为1,fruit为2.可以看出,默认以0开始,常量的值可以相同,比如
enum food {
meat=0, rice=0, fruit=0
};
未指定值的常量,默认从前一个常量的值开始递增,如下
enum food {
meat=7, rice, fruit
};
其中meat为7,rice为8,fruit为9