1. 结构体
(1)定义和使用
01 语法:struct 结构体名 { 结构体成员列表 };
struct Student
{
string name;
int age;
int score;
};
02 通过结构体创建变量的方式有三种,即使用结构体:
001 struct 结构体名 变量名
002 struct 结构体名 变量名 = {成员1值,成员2值,……}
003 定义结构体时顺便创建变量
// 001
struct Student s1;
s1.name = "张三";
s1.age = 12;
s1.score = 98;
cout << s1.name << endl;
// 002
struct Student s2 = {"张三", 12, 98};
cout << s2.name << endl;
// 003
struct Student
{
string name;
int age;
int score;
}s3;
s3.name = "张三";
s3.age = 12;
s3.score = 98;
cout << s3.name << endl;
2. 结构体数组
(1)作用
将自定义的结构体放入数组中方便维护。
(2)语法
struct 结构体名 数组名[元素个数] = { {}, {}, ……, {} }
struct Student arr[2] =
{
{"张三", 12, 98},
{"里斯", 20, 87}
};
//修改里斯为赵六
arr[1].name = "赵六";
//遍历结构体数组
for(int i=0; i<2; i++)
{
cout << arr[i].name << arr[i].age << arr[i].score << endl;
}
3. 结构体指针
(1)作用
通过指针访问结构体中的成员。
利用操作符 -> 可以通过结构体指针访问结构体属性。
(2)使用
struct Student s = {"张三", 12, 98};
//通过指针指向结构体变量
struct * p = &s;
//通过指针访问结构体变量中的数据
cout << p->name << endl;
cout << p->age<< endl;
cout << p->score<< endl;