结构体(日志19)
一、结构体基本概念
结构体属于用户自定义的数据类型,允许用户存储不同的数据类型
结构体的定义和使用
语法:struct 结构体名{ 结构体成员列表};
通过结构体创建变量的方式有3种:
- struct 结构体名 变量名
- struct 结构体名 变量名={成员1值,成员2值...}
- 定义结构体时顺便创建变量
示例:
#include<iostream>
#include<string.h>
using namespace std;
//结构体定义
//1.创建学生数据类型:学生包括(姓名,年龄,分数)
struct Student
{
//成员列表
string name;//姓名
int age;//年龄
int score;//分数
}s3;//顺便创建结构体变量
//2.通过学生类型创建具体学生
int main()
{
//2.1struct Student s1
//struct 关键字可以省略
struct Student s1;
//给s1属性赋值,通过.访问结构体变量中的属性
s1.name = "张三";
s1.age = 18;
s1.score = 100;
cout << "姓名:" << s1.name << "年龄:" << s1.age << "分数" << s1.score << endl;
//2.2struct Student s2={...}//赋初值
struct Student s2={"李四",19,80};
cout<<"姓名:"<< s2.name<<"年龄:" << s2.age<< "分数" << s2.score<< endl;
//2.3在定义结构体时顺便创建结构体变量
s3.name="王五";
s3.age=18;
s3.score=90;
cout<<"姓名:"<<s3.name<<"年龄:"<<s3.age<<"分数"<<s3.score<<endl;
return 0;
}
总结:
定义结构体时的关键字是struct,不可省略
创建结构体变量时,关键字struct可以省略
结构体变量利用操作符“ . ”访问成员
二、结构体数组
作用:将自定义的结构体放入到数组中方便维护
语法:struct 结构体名 数组名[元素个数]={ { },{ },...{ } };
#include<iostream>
#include<string.h>
using namespace std;
//1.定义结构体
struct Student
{
//姓名
string name;
//年龄
int age;
//分数
int score;
};
int main()
{
//2.创建结构体数组
struct Student stu[3] =
{
{"张三",18,100},
{"李四",19,80},
{"王五",18,80}
};
//3.给结构体数组中的元素赋值
stu[2].name = "赵六";
stu[2].age = 16;
stu[2].score = 99;
//4.遍历结构体数组
for (int i = 0; i < 3; i++)
{
cout << "姓名:" << stu[i].name << "年龄:" << stu[i].age << "分数:" << stu[i].score << endl;
}
return 0;
}
三、结构体指针
作用:通过指针访问结构体的成员
- 利用操作符
->可以通过结构体指针访问结构体属性
#include<iostream>
#include<string.h>
using namespace std;
//1.定义结构体
struct Student
{
//姓名
string name;
//年龄
int age;
//分数
int score;
};
int main()
{
//1.创建学生结构体变量
struct Student s1={"张三",17,95};
//2.通过指针指向结构体变量
struct Student *p=&s1;
//3.通过指针访问结构体变量中的数据
//通过结构体指针 访问结构体中的属性,需要利用‘->’
cout<<"姓名:"<<p->name<<"年龄:"<<p->age<<"分数:"<<p->score<<endl;
return 0;
}
总结:结构体指针可以通过->操作符,来访问结构体中的成员
四、结构体嵌套结构体
作用:结构体中的成员可以是另一个结构体
#include<iostream>
#include<string.h>
using namespace std;
//1.定义学生结构体
struct Student
{
//姓名
string name;
//年龄
int age;
//分数
int score;
};
//创建老师结构体
struct Teacher
{
//姓名
string name;
//编号
int id;
//年龄
int age;
//门下学生
struct Student stu;
};
int main()
{
//结构体嵌套结构体
//创建老师
Teacher t;
t.name = "老王";
t.id = 10087;
t.age = 45;
t.stu.name = "小明";
t.stu.age = 18;
t.stu.score = 90;
cout << "老师:" << t.name << "id:" << t.id << "年龄:" <<t.age<< endl;
cout << "学生:" << t.stu.name << "年龄:" << t.stu.age << "分数:" << t.stu.score;
return 0;
}
五、结构体做函数参数
作用:将结构体作为参数向函数中传递
传递方式有两种:
1.值传递
2.地址传递

