#include <iostream>
using namespace std;
//#include <string>
// 结构体语法: struct 结构体名称 { 结构体成员列表 }
// 自定义数据类型 一些类型集合组成的一个类型
struct student
{
string name;//姓名
int age;//年龄
int score;//分数
}s3; //顺便创建结构体变量
struct teacher {
int id;//职工编号
string name;//姓名
int age;//年龄
student student;//学生 (结构体嵌套结构体)
};
//打印结构体
//值传递
void printStruct(student s)
{
s.age = 30;
cout << s.name << endl << s.age << endl << s.score << endl;
}
//地址传递
void printStruct2(student *s)
{
s->age = 30;
//cout << (*s).name << endl << (*s).age << endl << (*s).score << endl;
cout << s->name << endl << s->age << endl << s->score << endl;
}
// 如果不想修改主函数中的教据,用值传递,反之用地址传递
int main()
{
// struct关键字可以省略
//struct student s1;
student s1;
s1.name = "Mike";
s1.age = 18;
s1.score = 95;
cout << s1.name << endl << s1.age << endl << s1.score << endl;
cout << "----------------" << endl;
student s2 = { "Andy",17,100 };
cout << s2.name << endl << s2.age << endl << s2.score << endl;
cout << "----------------" << endl;
s3.name = "YOYO";
s3.age = 19;
s3.score = 90;
cout << s3.name << endl << s3.age << endl << s3.score << endl;
cout << "----------------" << endl;
// 结构体数组
student arr[] = {
{"张三",18,85},
{"李四",19,100},
{"王五",20,95}
};
/*int len = sizeof(arr) / sizeof(arr[0]);
printarr(arr, len);*/
for (int i = 0; i < 3; i++)
{
cout << arr[i].name << endl << arr[i].age << endl << arr[i].score << endl;
}
cout << "----------------" << endl;
student s4 = { "小明",25,60 };
student *s5 = &s4;
cout << "姓名:" << s5->name << endl << "年龄:" << s5->age << endl << "分数:" << s5->score << endl;
cout << "----------------" << endl;
teacher t1 = {
123,"王老师",35,{"李华",18,93}
};
cout << "id:" << t1.id << endl << "姓名:" << t1.name << endl << "年龄:" << t1.age
<< endl << "学生:" << t1.student.name << "," << t1.student.age << "," << t1.student.score << endl;
cout << "----------------" << endl;
//printStruct(s4);
printStruct2(&s4);
cout << s4.name << endl << s4.age << endl << s4.score << endl;
system("pause");
return 0;
}
C++结构体
最新推荐文章于 2024-11-02 14:41:43 发布