用户自定义得数据类型,允许用户存储不同的数据类型
通俗的讲就是针对一个对象,将它的所有属性打包在一起访问,不用分别定义
一、结构体定义及使用(注意定义完后不能忘记;)
1、语法:struct 结构体名 {结构体成员列表};struct不可以省略
2、创建变量的三种方式:方式1,2常用,结构体关键字可以省略
1)struct 结构体名 变量名(然后通过.给变量赋值)
2)struct 结构 体名 变量名={成员值1,成员值2....}
3)定义结构体时顺便创建变量
#include<iostream>
using namespace std;
#include<string>
//1、创建学生数据类型:学生包括(姓名,年龄,分数)
//自定义数据类型,一些类型集合组成的一个类型
struct student
{
//成员列表
//姓名
string name;
//年龄
int age;
//分数
float score;
}s3;//创建方式3,在定义结构体时就创建结构体变量
//2、通过学生类型创建具体学生
int main()
{
struct student s1;//创建方式1
s1.name = "张三";//给s1属性赋值,通过.访问结构体变量中的属性
s1.age = 21;
s1.score = 150;
cout << "姓名:" << s1.name << "年龄:" << s1.age << "成绩:"<< s1.score << endl;
struct student s2 = { "李四",19,80 };//创建方式2
cout << "姓名:" << s2.name << "年龄:" << s2.age << "成绩:" << s2.score << endl;
s3.name = "王五";
s3.age = 20;
s3.score = 110;
cout << "姓名:" << s3.name << "年龄:" << s3.age << "成绩:" << s3.score << endl;
}
二、结构体数组
将自定义的结构体放入数组中方便维护。
将结构体变量(有多个属性)放在数组中。类比普通数组,struct student是类型 ,那么后面跟数组名,数组大小,然后赋值。只是赋值时以前是给相同类型的值,由于现在定义了结构体那么里面就是结构体变量的属性,可以通过数组的访问方式再通过.的方式依次访问到各个属性。
1、语法:struct 结构体名 数组名[元素个数]={{},{}.....{}}
在这之前得先定义结构体
#include<iostream>
using namespace std;
#include<string>
//结构体数组
//1、定义结构体
struct student
{
string name;
int age;
int score;
};
int main()
{
//2、创建结构体数组
//3、给结构体中的元素赋值
struct student stuarray[3] = {
{"张三",18,100},
{"李四",19,88},
{"王五",22,110}
};
//后期可以修改数组中的元素
stuarray[2].name = "赵六";
//4、遍历结构体数组
for (int i = 0; i < 3; i++)
{
cout << "姓名:"<<stuarray[i].name << " " << "年龄:"<<stuarray[i].age << " " << "分数:" << stuarray[i].score;
cout << endl;
}
}
三、结构体指针
通过指针访问结构体中得成员。
定义指针时要注意与以前不同得是注意指针类型的不同,并且输出时由于结构体的特殊性,还得指针指向属性(平常普通的只需*p即可访问输出)。
通过->可以通过结构体指针访问结构体属性。
#include<iostream>
using namespace std;
#include<string>
//1、结构体指针
//定义结构体
struct student
{
string name;
int age;
int score;
};
int main()
{
//创建学生结构体变量
struct student s1 = { "张三",24,123 };
//通过指针指向结构体变量
struct student* p = &s1;
//通过指针访问结构体变量中得属性
cout << "姓名:" << p->name << " " << "年龄:" << p->age << " " << "分数:" << p->score << endl;
}