1.结构体数组
2.结构体指针
#include <iostream>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
int main()
{
//结构体数组
//1.创建
struct Student stuArray[] =
{
{"张三",18,10},
{"李四",10,1090},
{"王五",88,125},
};
//2.赋值
stuArray[0].name = "蔡徐坤";
stuArray[1].age = 66;
stuArray[2].score = 25;
//3.便历
for (int i = 0; i < 3; i++) {
cout << stuArray[i].name
<< "年龄:" << stuArray[i].age
<< "分数:" << stuArray[i].score << endl;
}
cout << "*********************" << endl;
//结构体指针
//1.创建
struct Student stu1 = { "坤坤",21,20 };
//2.指针指向结构体变量
Student* p = &stu1;
//3.指针访问结构体变量
//通过结构体指针访问结构体中的属性,需要利用 ‘->’
cout << p->name
<< "年龄:" << p->age
<< "分数:" << p->score << endl;
system("pause");
return 0;
}
结果
蔡徐坤年龄:18分数:10
李四年龄:66分数:1090
王五年龄:88分数:25
*********************
坤坤年龄:21分数:20
请按任意键继续. . .
3.结构体嵌套
4.结构体做函数参数
#include <iostream>
using namespace std;
//结构体嵌套
struct Student
{
string name;
int age;
int score;
};
struct Teacher
{
int id;
string name;
int age;
struct Student s1;
};
//结构体做函数参数
//1.值传递
void printStudent(struct Student s)
{
s.age = 100;//修饰形参,实参不会改变
cout << "子函数中 姓名:" << s.name
<< "年龄:" << s.age
<< "分数:" << s.score << endl;
}
//2.地址传递
void printStudent2(struct Student* s)//用指针还会减少内存空间
{
s->age = 100;//修饰形参会改变实参
cout << "子函数2中 姓名:" << s->name
<< "年龄:" << s->age
<< "分数:" << s->score << endl;
}
int main()
{
//结构体嵌套
Teacher t1;
t1.id = 25410;
t1.name = "老王";
t1.age = 35;
t1.s1.name = "小王";
t1.s1.age = 20;
t1.s1.score = 100;
//结构体做函数参数
printStudent(t1.s1);
cout << "main函数值传递中 姓名:" << t1.s1.name
<< "年龄:" << t1.s1.age
<< "分数:" << t1.s1.score << endl;
printStudent2(&t1.s1);
cout << "main函数地址传递中 姓名:" << t1.s1.name
<< "年龄:" << t1.s1.age
<< "分数:" << t1.s1.score << endl;
system("pause");
return 0;
}
结果
子函数中 姓名:小王年龄:100分数:100
main函数值传递中 姓名:小王年龄:20分数:100
子函数2中 姓名:小王年龄:100分数:100
main函数地址传递中 姓名:小王年龄:100分数:100
请按任意键继续. . .