1、结构体基本概念
结构体属于用户自定义的数据类型,允许用户存储不同类型的数据。
2、结构体定义和使用
语法:struct (结构体变量名) {成员列表}
结构体的创建方式有三种
- struct 结构体 变量名
- struct 结构体 变量名={.....}
- 在定义结构体的时候顺便创建变量
示例:
// 1、结构体定义
struct Student
{
//成员列表
string name; //姓名
int age; //年龄
float score; // 分数
} stu3; // 第三种创建方式
int main()
{
// 结构体创建方式1
struct Student s1;
s1.age = 18;
s1.name = "zhaosi";
s1.score = 100;
// 结构体创建方式2
struct Student s2 = { "lisi",19,87 };
// 第三种
}
3、结构体数组
结构体数组:将用户自定义的结构体变量放到数组中,便于维护
语法:struct (数组名[元素个数])={{},{},.....{}}
示例:
#include<iostream>
#include<string>
using namespace std;
struct Student
{
string name;
int age;
float score;
};
int main()
{
// 创建结构体数组
Student arr[3] = {
{"zhangsan",18,50.8},
{"lisi", 19,78},
{"wangwu",20,100}
};
// 修改结构体数组中元素值
arr[2].name = "zhailou";
// 遍历结构体数组
for (int i = 0; i < 3; i++)
{
cout << "姓名:" << arr[i].name <<" "
<< "年龄 :" <<arr[i].age <<" "
<< "成绩:" << arr[i].score << endl;
}
}
4、结构体指针
通过指针访问结构体中的成员。
示例:
#include<iostream>
#include<string>
using namespace std;
//结构体定义
struct Student
{
//成员列表
int age; //年龄
string name; // 姓名
float score; // 分数
};
int main()
{
// 创建结构体变量
Student s1 = { 18,"Wangwu",78.9 };
// 创建指针指向结构体变量
Student* p = &s1;
// 访问结构体变量中的数据
// 通过指针访问结构体需要用->符号
cout << "姓名:" << p->name << "年龄:" << p->age << "分数:" << p->score;
}
5、结构体嵌套结构体
作用:结构体中的成员是另一个结构体
#include<iostream>
#include<string>
using namespace std;
//学生结构体定义
struct Student
{
//成员列表
int age; //年龄
string name; // 姓名
float score; // 分数
};
// 教师结构体定义
struct Teacher {
// 成员列表
int id; // 职工编号
string name; //教师姓名
int age; //教师年纪
struct Student s1;//指导的学生 子结构体
};
int main()
{
// 创建结构体变量
Student s1 = { 18,"Wangwu",78.9 };
Teacher t1 = { 2,"Zhu",78,s1 };
// 创建指针指向结构体变量
Teacher* p = &t1;
// 访问结构体变量中的数据
// 通过指针访问结构体需要用->符号
cout << "姓名:" << p->name << "年龄:" << p->age << "分数:" << p->s1.score;
}
6、结构体做函数参数
作用:将结构体作为参数向函数中传递
传递方式:
- 值传递
- 地址传递
// 1、结构体定义 struct Student { //成员列表 string name; int age; float score; }; // 值传递 void printStruct(struct Student s) { cout << s.name<<endl; cout << s.age << endl; cout << s.score << endl; } // 地址传递 void printStruct2(struct Student* p) { p->age = 100; cout << p->name << endl; cout << p->age << endl; cout << p->score<< endl; } int main() { struct Student s1; s1.age = 18; s1.name = "zhaosi"; s1.score = 100; struct Student s2 = { "lisi",19,87 }; printStruct2(&s2); printStruct(s2); }