1、结构体数据定义及访问
#include<iostream>
#include<string>
using namespace std;
//1、结构体定义:struct 结构体名 {结构体成员列表};
struct Student
{
string name;
int age;
int score;
};
//2、通过学生类型创建具体的学生(3种方法)
int main()
{
//2.1 struct Student s1
struct Student s1;
s1.name="小王";
s1.age = 13;
s1.score=90;
cout<<"姓名:"<<s1.name<<" 年龄:"<<s1.age<<" 分数:"<<s1.score<<endl;
//2.2 struct Student s2 ={...}
struct Student s2 ={"李四",19,89};
cout<<"姓名:"<<s2.name<<" 年龄:"<<s2.age<<" 分数:"<<s2.score<<endl;
//2.3 在定义结构体变量时顺便创建结构体变量
struct Student1
{
string name;
int age;
int score;
}s3;
s3.name="赵六";
s3.age=18;
s3.score=78;
cout<<"姓名:"<<s3.name<<" 年龄:"<<s3.age<<" 分数:"<<s3.score<<endl;
}
2、结构体与数组
#include<iostream>
#include<string>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
int main()
{
//1、创建结构体数组
struct Student starry[3]=
{
{"张三",18,100},
{"李四",30,98},
{"赵六",23,88}
};
//2、给结构体中的元素赋值
starry[0].name="梅子";
starry[0].age=46;
starry[0].score=60;
//3、结构体遍历
for(int i=0;i<3;i++)
{
cout<<"姓名:"<<starry[i].name<<" 年龄:"<<starry[i].age<<" 分数:"<<starry[i].score<<endl;
}
}
3、结构体与指针
#include<iostream>
#include<string>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
int main()
{
//1、创建结构体变量
struct Student s1={"王麻子",20,89};
//2、通过指针指向结构体变量
struct Student *p=&s1;
//3、通过指针访问结构体变量当中的数据
cout<<"姓名:"<<p->name<<" 年龄:"<<p->age<<" 分数:"<<p->score<<endl;
}
4、结构体的嵌套
#include<iostream>
#include<string>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
struct Teacher
{
string name;
int id;
int age;
struct Student stu;
};
int main()
{
struct Teacher t={"d",12,56};
t.stu.name="dsf";
t.stu.age=34;
t.stu.score=90;
cout<<t.name<<t.age<<t.stu.name<<endl;
}
5、结构体作为函数的参数
函数当中地址传递可以节省内存(但如果修改值时,其原来的值也变了)
#include<iostream>
#include<string>
using namespace std;
//值传递(修饰形参数后,实参不改变)和地址传递(修饰形参数后,实参改变)两种
struct Student
{
string name;
int age;
int score;
};
void printstudentzhi(struct Student s1)
{
cout<<"姓名:"<<s1.name<<" 年龄"<<s1.age<<" 分数"<<s1.score<<endl;
}
void printstudentdizhi(struct Student *s1)
{
cout<<"姓名:"<<s1->name<<" 年龄"<<s1->age<<" 分数"<<s1->score<<endl;
}
int main()
{
struct Student s1={"赵武",23,89};
//printstudentzhi(s1); //值传递
printstudentdizhi(&s1); //地址传递
}
6、const加上后(地址传递),原来数据不能被修改
#include<iostream>
#include<string>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
void printstudentdizhi(const Student *s1)
{
//s1->name="王五";//加了const后此处报错,不接受修改
cout<<"姓名:"<<s1->name<<" 年龄"<<s1->age<<" 分数"<<s1->score<<endl;
}
int main()
{
struct Student s1={"赵武",23,89};
printstudentdizhi(&s1); //地址传递
cout<<"姓名:"<<s1.name<<" 年龄"<<s1.age<<" 分数"<<s1.score<<endl;
}