结构体属于用户自定义的数据类型,允许用户存储不同的数据类型
一、结构体使用方式
1.1 结构体创建变量的三种方式
方式一
- 结构体中使用基本数据类型进行变量声明,默认变量的访问权限都是public的
先声明后赋值
struct Student
{
//结构体中不能使用类,只能使用基本数据类型
char name[16];
int age;
int score;
};
struct Student stu1;
stu1.name = "张一";
stu1.age = 13;
stu1.score = 100;
方式二:
直接使用花括号赋值
//方式二
struct Student stu2 = { "李四",19,60 };
方式三:
在结构体上声明变量
struct Student
{
//成员列表
string name; //姓名
int age; //年龄
int score; //分数
//在结构体中嵌套一个类
Teacher t;
}stu3; //结构体变量创建方式3
//方式三
stu3 = { "李四",19,60 };
1.2 结构体数组
//结构体数组的声明方式
struct Student arr[3] = {
{"张三",18,99},
{"李四",17,59},
{"王五",16,57},
};
可以使用正常的for循环来对数组进行遍历
1.3 结构体指针
class Teacher {
public:
int age;
string name;
};
struct Student
{
//成员列表
string name; //姓名
int age; //年龄
int score; //分数
//在结构体中嵌套一个类
Teacher t;
}; //结构体变量创建方式3
struct Student stu1;
stu1.name = "张一";
stu1.age = 13;
stu1.score = 100;
stu1.t.age = 10;
stu1.t.name = "张老师";
struct Student* p = &stu1;
p->age = 14;
cout << "结构体中通过修改之后的学生年龄为" << stu1.age << endl;

通过指针修改之后的打印情况
1.4 结构体嵌套结构体
结构体嵌套结构体
struct Student
{
//成员列表
string name; //姓名
int age; //年龄
int score; //分数
//在结构体中嵌套一个类
Teacher t;
}stu3; //结构体变量创建方式3
struct teacher {
int id;
string name;
int age;
struct Student stu;
};
1.5 结构体做函数参数
方法一:
值传递
void dostruct(struct Student stu) {
stu.age = 10;
cout << "方法调用结构体修改之后的学生年龄为" << stu.age << endl;
}
main函数中调用
dostruct(stu2);
方法二:
址传递
void dostruct(struct Student *stu) {
stu-> age = 11;
cout << "方法调用结构体修改之后的学生年龄为" << stu->age << endl;
}
函数中传递的是一个指针
main函数中调用,传递的实参是地址
dostruct(&stu2);
1.6 结构体中const使用场景
在函数的形参上面加上const修饰符修饰,可以防止函数中对结构体数据进行修改
//加上const防止对结构体中的数据进行误操作
void dostruct( const struct Student* stu) {
//stu->age = 11; 加了const修饰之后不能修改结构体中的数据
cout << "方法调用结构体修改之后的学生年龄为" << stu->age << endl;
}