h5婚纱摄影网站模板,做网站的画布是多少,知更鸟wordpress模板,岳阳做网站哪家好1 概述
结构体是用户自定义的数据类型#xff0c;可以包含不同的数据类型
2 定义和使用
定义一个学生的结构体
//结构体定义
struct student
{//成员列表string name; //姓名int age; //年龄int score; //分数
}stu3; //结构体变量创建方式3 int main() {//结构体…1 概述
结构体是用户自定义的数据类型可以包含不同的数据类型
2 定义和使用
定义一个学生的结构体
//结构体定义
struct student
{//成员列表string name; //姓名int age; //年龄int score; //分数
}stu3; //结构体变量创建方式3 int main() {//结构体变量创建方式1struct student stu1; //struct 关键字可以省略stu1.name 张三;stu1.age 18;stu1.score 100;cout 姓名 stu1.name 年龄 stu1.age 分数 stu1.score endl;//结构体变量创建方式2struct student stu2 { 李四,19,60 };cout 姓名 stu2.name 年龄 stu2.age 分数 stu2.score endl;stu3.name 王五;stu3.age 18;stu3.score 80;cout 姓名 stu3.name 年龄 stu3.age 分数 stu3.score endl;return 0;
}上面展示了三种方式创建结构体变量第一种方式是通过struct 结构体名 变量名创建然后依次给其中存储的成员初始化。第二种方式是创建变量的时候一并使用大括号初始化结构体变量。第三种方式是创建结构体定义的时候直接创建一个变量。 结构体变量访问结构体中的成员使用“.”成员运算符访问 创建结构体变量的时候struct关键字可以省略 结构体变量的大小是结构体中各个元素大小的和
3 结构体数组
结构体数据就是结构体变量组成的数组
//结构体定义
struct student
{//成员列表string name; //姓名int age; //年龄int score; //分数
}int main() {//结构体数组struct student arr[3]{{张三,18,80 },{李四,19,60 },{王五,20,70 }};for (int i 0; i 3; i){cout 姓名 arr[i].name 年龄 arr[i].age 分数 arr[i].score endl;}return 0;
}4 结构体指针
结构体可以作为参数传递但是结构体作为参数时与传值相同会将整个结构体赋值成一个副本然后给形参。如果结构体存储的数据很大的话拷贝会影响性能所以可以使用指针进行传参。 结构体指针用于指向结构体变量的地址
struct student stu { 张三,18,100, };
struct student * p stu;5 结构体嵌套
结构体中可以包含结构体变量
//学生结构体定义
struct student
{//成员列表string name; //姓名int age; //年龄int score; //分数
};//教师结构体定义
struct teacher
{//成员列表int id; //职工编号string name; //教师姓名int age; //教师年龄struct student stu; //子结构体 学生
};6 结构体作为参数
//学生结构体定义
struct student
{//成员列表string name; //姓名int age; //年龄int score; //分数
};//值传递
void printStudent(student stu )
{stu.age 28;cout 子函数中 姓名 stu.name 年龄 stu.age 分数 stu.score endl;
}//地址传递
void printStudent2(student *stu)
{stu-age 28;cout 子函数中 姓名 stu-name 年龄 stu-age 分数 stu-score endl;
}int main() {student stu { 张三,18,100};//值传递printStudent(stu);cout 主函数中 姓名 stu.name 年龄 stu.age 分数 stu.score endl;cout endl;//地址传递printStudent2(stu);cout 主函数中 姓名 stu.name 年龄 stu.age 分数 stu.score endl;return 0;
}这里涉及值传递和地址传递两种方式结构体数据大时推荐使用地址传递能够减小性能消耗
7 结构体中使用const
结构体指针作为参数时可以使用const修饰以防数据被修改
//学生结构体定义
struct student
{//成员列表string name; //姓名int age; //年龄int score; //分数
};//const使用场景
void printStudent(const student *stu) //加const防止函数体中的误操作
{//stu-age 100; //操作失败因为加了const修饰cout 姓名 stu-name 年龄 stu-age 分数 stu-score endl;}int main() {student stu { 张三,18,100 };printStudent(stu);system(pause);return 0;
}这里添加了const修饰是常量指针指针指向的值不能修改。