文章目录
一、结构体
(一)结构体的基本概念
结构体属于用户自定义的数据类型,允许用户存储不同的数据类型
(二)结构体的定义和使用
练习代码如下:
#include <iostream>
#include <string>
using namespace std;
//创建学生数据类型
//自定义数据类型:一些内置类型集合组成的一个类型
struct Student
{
string name;//姓名
int age;//年龄
int score;//分数
};
int main()
{
//通过学生类型创建出具体学生
//第一种方式:
struct Student s1;
s1.name = "zhangsan";
s1.age = 18;
s1.score = 100;
cout << "姓名: " << s1.name << endl;
cout << "年龄: " << s1.age << endl;
cout << "分数: " << s1.score << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
//创建学生数据类型
//自定义数据类型:一些内置类型集合组成的一个类型
struct Student//struct关键字不可以省略
{
string name;//姓名
int age;//年龄
int score;//分数
};
int main()
{
//第二种定义方式:
struct Student s2 = {
"lisi",20,98 };//struct关键字可以省略
cout << "姓名: " << s2.name << endl;
cout << "年龄: " << s2.age << endl;
cout << "分数: " << s2.score << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
//创建学生数据类型
//自定义数据类型:一些内置类型集合组成的一个类型
struct Student
{
string name;//姓名
int age;//年龄
int score;//分数
}s3;
int main()
{
//第三种定义方式
s3.name = "wangwu";
s3.age = 21;
s3.score = 67;
cout << "姓名: " << s3.name << endl;
cout << "年龄: " << s3.age << endl;
cout << "分数: " << s3.score << endl;
return 0;
}
注意:
- 定义结构体时struct关键字不可以省略
- 创建结构体变量时struct关键字可以省略
- 通过
.
的方式访问结构体的成员变量
(三)结构体数组
作用:将自定义的结构体放入到数组中方便维护
语法:
struct 结构体名 数组名[元素个数] =
{
{
},{
},...,{
}}
练习代码如下:
#include <iostream>
#include <string>
using namespace std;
//创建学生数据类型
//自定义数据类型:一些内置类型集合组成的一个类型
struct Student
{
string name;//姓名
int age;//年龄
int score;//分数
};
int main()
{
//创建结构体数组,并对数组元素赋值
struct Student stuarr[3