文章目录
一.结构体的概述
结构体的作用:结构体可以用来自己定义数据类型,也可以存储不同的数据类型。
例如,我们可以写个学生或老师的数据类型。
struct关键字可以省略,也不可以不省略,只是加了struct,我们就能马上知道它是结构体。
二.结构体的定义和使用
1.结构体的定义
结构体的语法:struct 结构体名 {结构体属性列表}
struct student {string name,int age,int score};
2.创建结构体变量的三种方式
①struct 结构体名 {属性1;属性2;属性3};
#include<iostream>
using namespace std;
//1.创建学生数据类型:学生属性包含(姓名,年龄,分数)
struct Student
{
//属性列表
string name;
int age;
int score;
};
int main()
{
//2.通过学生类型创建具体学生,所以s就为变量了。
struct Student s;
//通过结构体进行赋值
s.name = "张三";
s.age = 10;
s.score = 100;
//通过结构体访问属性值
cout << "姓名:" << s.name << endl;
cout << "年龄:" << s.age << endl;
cout << "分数:" << s.score << endl;
return 0;
}
②struct 结构体名{属性1的值,属性2的值,属性3的值};
#include<iostream>
using namespace std;
//1.创建学生数据类型:学生属性包含(姓名,年龄,分数)
struct Student
{
//属性列表有了初始值
string name="张三";
int age=10;
int score=100;
};
int main()
{
//2.通过学生类型创建具体学生,所以s就为变量了。
struct Student s;
//通过结构体访问属性值
cout << "姓名:" << s.name << endl;
cout << "年龄:" << s.age << endl;
cout << "分数:" << s.score << endl;
return 0;
}
③定义结构体时,顺便创建变量
#include<iostream>
using namespace std;
//1.创建学生数据类型:学生属性包含(姓名,年龄,分数)
struct Student
{
//属性列表有了初始值
string name="张三";
int age=