1、结构体定义和使用
结构体创建变量的三种方式
1、struct 结构体名 变量名
2、struct 结构体名 变量名={成员1值, 成员2值}
#include <iostream>
#include<string>
using namespace std;
struct Student{
string name;
int age;
int score;
};
int main()
{
//创建方式1
struct Student s1; //这里的struct可以省略
//给S1属性赋值
s1.name="张三";
s1.age=18;
s1.score=30;
cout<<"姓名: "<<s1.name<<" 年龄: "<<s1.age<<" 分数: "<<s1. score<<endl;
//创建方式2
struct Student s2={"李四",12,90};
cout<<"姓名: "<<s2.name<<" 年龄: "<<s2.age<<" 分数: "<<s2. score<<endl;
return 0;
}
3、定义结构体时顺便创建变量
#include <iostream>
#include<string>
using namespace std;
struct Student{
string name;
int age;
int score;
}s3;
int main()
{
//创建方式3
s3.name="王麻子";
s3.age=20;
s3.score=22;
cout<<"姓名: "<<s3.name<<" 年龄: "<<s3.age<<" 分数: "<<s3. score<<endl;
return 0;
}
2、结构体数组
#include <iostream>
#include<string>
using namespace std;
struct Student{
string name;
int age;
int score;
};
int main()
{
struct Student stuArray[8]=
{
{"张三",18,20},
{"李四",10,30},
{"王麻子",28,20}
};
for(int i=0;i<3;i++)
{
cout<<"姓名: "<<stuArray[i].name<<" 年龄: "<<stuArray[i].age<<" 分数: "<<stuArray[i]. score<<endl;
}
return 0;
}
3、结构体指针
使用->访问
#include <iostream>
#include<string>
using namespace std;
struct Student{
string name;
int age;
int score;
};
int main()
{
struct Student s={"张三",19,20};
//2、通过指针指向结构体变量
Student *p = &s;
cout<<"姓名: "<<p->name<<" 年龄: "<<p->age<<" 分数: "<<p->score<<endl;
return 0;
}
4、结构体嵌套结构体
#include <iostream>
#include<string>
using namespace std;
struct Student{
string name;
int age;
int score;
};
struct Teacher{
string name;
int age;
struct Student stu; //嵌套的结构体
};
int main()
{
//创建老师
Teacher t;
t.name="老王";
t.age=90;
t.stu.name="小王";
t.stu.age=18;
t.stu.score=60;
cout<<"姓名: "<<t.name<<" 年龄: "<<t.age<<" 学生:"<<t.stu.name<<" 学生年龄:"<<t.stu.age<<
" 学生的成绩:"<<t.stu.score<<endl;
return 0;
}
5、结构体做函数参数
值传递和地址传递的区别:在函数中值传递,不改变整个变量的值,只改变函数内部的值;但是函数中地址传递,函数中改变参数的值,整个值就会发生改变,
#include <iostream>
#include<string>
using namespace std;
struct Student{
string name;
int age;
int score;
};
//第一种传参方式,值传递
void printStudenInfo1(struct Student s)
{
s.name="李四";
cout<<"方式1 姓名: "<<s.name<<" 年龄: "<<s.age<<" 分数: "<<s. score<<endl;
}
//第2种传参方式,地址传递
void printStudenInfo2(struct Student *s)
{
s->name="王麻子";
cout<<"方式2 姓名: "<<s->name<<" 年龄: "<<s->age<<" 分数: "<<s->score<<endl;
}
int main()
{
struct Student s={"张三",18,20};
//第一种传参方式,值传递
printStudenInfo1(s);
cout<<"主函数中显示 姓名: "<<s.name<<" 年龄: "<<s.age<<" 分数: "<<s. score<<endl;
//第2种传参方式,地址传递
printStudenInfo2(&s);
cout<<"主函数中显示 姓名: "<<s.name<<" 年龄: "<<s.age<<" 分数: "<<s. score<<endl;
return 0;
}