1、结构体
1.1结构体数组
作用:将自定义的结构体放入到数组中方便维护
语法:struct 结构体名 数组名【元素个数】={ {},{},…{} }。每一个大括号内都是一个结构体。
使用"."访问结构体中元素,结构体数组中的元素定义后也可以按照下面所写的给结构体元素赋值部分修改。
#include<iostream>
using namespace std;
#include<string>
//结构体定义
struct Student
{
string name;
int age;
int score;
};
int main() {
//结构体数组
struct Student stdarray[3]=
{
{
"张三",18,100},
{
"李四",28,99},
{
"王五",38,66}
};
//给结构体数组中的元素赋值
stdarray[2].age = 28;
stdarray[2].name = "赵六";
stdarray[2].score = 97;
//遍历结构体数组
for (int i = 0; i < 3; i++) {
cout << "姓名:" << stdarray[i].name
<< "年龄:" << stdarray[i].age
<< "分数:" << stdarray[i].score << endl;
}
system("pause");
return 0;
}
1.2结构体指针
作用:使用指针访问结构体中的成员
利用操作符“->”可以利用结构体指针访问结构体属性
在定义结构体时,关键字struct不可省略,在创建结构体变量时可以省略,定义结构体指针,变量类型也为结构体类型。
#include<iostream>
using namespace std;
#include<string>
//结构体定义
struct Student
{
string name;
int age;
int score;
};
int main() {
//创建结构体变量
struct Student s = {
"张三",18,100 };
//通过指针指向结构体变量
Student* p = &s;
//通过指针访问结构体变量中的数据
cout << "姓名:" << p->name
<<</