目录
结构体定义:
结构体属于用户自定义的数据类型,允许用户存储不同的数据类型
语法:struct 结构体{结构体成员列表};
通过结构体创建变量有3种方式:
1.struct 结构体名 变量名
2.struct 结构体名 变量名={成员1值,成员2值}
3.定义结构体时顺便创建变量
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
//1、创建学生数据类型:学生包括(姓名、年龄、分数)
//自定义数据类型,一些类型集合组成的一个类型
struct Student //定义结构体struct不可省
{
//成员列表
string name;//姓名
int age;//年龄
int score;//分数
}s3;//顺便创建结构体变量
//2、通过学生类型创建具体学生
int main()
{
//2.1 struct Student s1
struct Student s1; //创建结构体变量时,struct 关键字可以省略 Student s1;
s1.name = "张三"; //给s1属性赋值,通过 . 访问结构体变量中的属性
s1.age = 18;
s1.score = 100;
cout << "姓名:" << s1.name << " 年龄:" << s1.age << " 分数:" << s1.score<<endl;
//2.2 struct Student s2={...........}
struct Student s2 = { "李四",19,20 };
cout << "姓名:" << s2.name << " 年龄:" << s2.age<< " 分数:" << s2.score << endl;
//2.3 在定义结构体时顺便创建结构体变量
s3.name = "王五";
s3.age = 20;
s3.score = 60;
cout << "姓名:" << s3.name << " 年龄:" << s3.age << " 分数:" << s3.score << endl;
system("pause");
return 0;
}
结构体数组
作用:将自定义的结构体放入到数组中方便维护
语法:struct 结构体名 数组名{元素个数}={
{ },{ },...{ }}
//1、定义结构体
struct Student
{
//成员列表
string name;//姓名
int age;//年龄
int score;//分数
};
int main()
{
//2、创建结构体数组
struct Student stuArray[3] =
{
{"李四",19,20},
{"张三",24,44},
{"王五",23,45}
};
//3、给结构体数组中的元素赋值
stuArray[2].name = "赵六";
stuArray[2].age = 21;
//4、遍历结构体数组
for (int i = 0; i < 3; i