- 自定义的数据类型,允许存储不同数据类型
定义及使用
#include<iostream>
#include <string>
using namespace std;
// 结构体类型定义
struct student
{
//成员列表(属性)
//姓名
string name;
//年龄
int age;
//分数
int score;
}stu3;
int main()
{
// .索引赋值
struct student stu1;
stu1.name = "张三";
stu1.age = 20;
stu1.score = 60;
cout << "姓名" << stu1.name << endl << "年龄" << stu1.age << endl << "成绩" << stu1.score << endl;
// 直接对应赋值
struct student stu2 = {"李四",20,56};
// 定义时创建后赋值
stu3.name = "王五";
stu3.age = 20;
stu3.score = 78;
cout << "姓名" << stu3.name << endl << "年龄" << stu3.age << endl << "成绩" << stu3.score << endl;
return 0;
}
结构体数组
//结构体数组定义
struct studentgroup
{
string name1;
int age1;
int score1;
};
//结构体数组
int main()
{
struct studentgroup arry[3] =
{
{"张三",20,60},
{"李四",20,56},
{"王五",20,78}
};
arry[2].name1 = "赵六"; //点索引
for(int i = 0;i<3;i++)
{
cout << "姓名" << arry[i].name1 << endl << "年龄" << arry[i].age1 << endl << "成绩" << arry[i].score1 << endl;
}
return 0;
}
结构体指针
- **->**访问结构体
// 指针访问结构体
struct student* p = &stu1;
cout << "姓名" << p->name << endl << "年龄" << p->age << endl << "成绩" << p->score << endl;
结构体嵌套
例:每个老师辅导一个学员,一个老师的结构体中,记录一个学生的结构体
//定义
struct teacher
{
int id;
string name;
struct student stu;
};
结构体与函数
值传递
传入结构体值
void printstudent1(struct student stu)
{
cout << "姓名" << stu.name << endl << "年龄" << stu.age << endl << "成绩" << stu.score << endl;
}
地址传递
传入结构体地址,使用指针访问
void printstudent2(struct student* p)
{
cout << "姓名" << p->name << endl << "年龄" << p->age << endl << "成绩" << p->score << endl;
}
结构体中的const
void printstudent2(const struct student* p)
限定结构体内存为常量