一、结构体数组
存放相同组合的大量数据时,可以通过创建结构体数组的方式进行;
struct Student
{
string name;
int age;
int score;
};
int main()
{
Student stuArray[3] =
{
{"汪苏泷",34,10000},
{"不分手的恋爱",12,10000},
{"还是想念",0,10000}
};
for (int i = 0; i < 3; i++)
{
cout << " name: " << stuArray[i].name
<< " age: " << stuArray[i].age
<< " score: " << stuArray[i].score << endl;
}
system("pause");
return 0;
}
二、结构体指针
可以通过指针来访问结构体中的成员,利用‘->’符号;
struct Student
{
string name;
int age;
int score;
};
int main()
{
//创建结构体变量
Student s = {"汪苏泷",34,10000};
//通过指针指向结构体变量
Student* p = &s;
//通过指针访问结构体变量中的数据
cout << "姓名:" << p->name << " 年龄:" << p->age << " 分数:" << p->score << endl;
system("pause");
return 0;
}
三、结构体嵌套结构体
通过两个‘.’,可以访问结构体中结构体的数据;例如如下代码是在teacher结构体中嵌套了stuent结构体;
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
struct Teacher
{
string name;
int age;
int id;
struct Student stu;
};
int main()
{
Teacher t;
t.id = 0001;
t.age = 18;
t.name = "李雪琴";
t.stu.age = 34;
t.stu.name = "汪苏泷";
t.stu.score = 10000;
cout << "姓名:" << t.name << " 年龄:" << t.age << " id:" << setfill('0') << setw(4) << t.id<< endl;
cout << "学生姓名:" << t.stu.name << " 年龄:" << t.stu.age<< " 分数:" << t.stu.score << endl;
system("pause");
return 0;
}
运行结果如下: