8.结构体
8.5 结构体嵌套结构体
作用: 结构体中的成员可以是另一个结构体。 示例: 每个老师辅导一个学生,一个老师的结构体中,记录一个学生的结构体。
#include <iostream>
using namespace std;
struct student
{
string name;
int age;
int score;
};
struct teacher
{
int id;
string name;
int age;
struct student stu;
};
int main()
{
teacher t = { 100, "老王", 50, {"小王", 20, 95} };
cout << t.id << " "
<< t.name << " "
<< t.age << " "
<< t.stu.name << " "
<< t.stu.age << " "
<< t.stu.score << endl;
system("pause");
return 0;
}
8.6 结构体做函数参数
作用: 将结构体作为参数向函数中传递。 传递方式: (1)值传递;(2)地址传递。
#include <iostream>
using namespace std;
struct student
{
string name;
int age;
int score;
};
void printStudent1(student s)
{
cout << " 姓名:" << s.name
<< ";年龄:" << s.age
<< ";分数:" << s.score << endl;
}
void printStudent2(student* p)
{
cout << " 姓名:" << p->name
<< ";年龄:" << p->age
<< ";分数:" << p->score << endl;
}
int main()
{
student s = { "张三",20,89 };
printStudent1(s);
printStudent2(&s);
system("pause");
return 0;
}
8.7 结构体中const使用场景
作用: 用const来防止误操作。
#include <iostream>
using namespace std;
struct student
{
string name;
int age;
int score;
};
void printStudent(const student *s)
{
cout << " 姓名:" << s->name
<< " 年龄:" << s->age
<< " 分数:" << s->score << endl;
}
int main()
{
student s = { "张三",15,70 };
printStudent(&s);
system("pause");
return 0;
}
|