结构体的定义和使用
#include<iostream>
using namespace std;
#include<string>
struct Student
{
string name;
int age;
int score;
}s3;
int main(){
struct Student s1;
s1.name="张三";
s1.age=18;
s1.score=100;
cout<<"名字"<<s1.name<<"年龄"<<s1.age<<"成绩"<<s1.score<<endl;
struct Student s2={"李四",19,80 };
cout<<"名字"<<s2.name<<"年龄"<<s2.age<<"成绩"<<s2.score<<endl;
s3.name="王五";
s3.age=19;
s3.score=90;
cout<<"名字"<<s3.name<<"年龄"<<s3.age<<"成绩"<<s3.score<<endl;
return 0;
}
结构体数组
#include<iostream>
using namespace std;
#include<string>
struct Student
{
string name;
int age;
int score;
};
int main(){
struct Student arr[3]=
{
{"张三",18,100},
{"李四", 19,80},
{"王五", 19,90}
};
arr[2].name="赵六";
arr[2].age=22;
arr[2].score=99;
for(int i=0;i<3;i++)
{
cout<<"名字"<<arr[i].name<<"年龄"<<arr[i].age<<"成绩"<<arr[i].score<<endl;
}
return 0;
}
结构体指针
#include<iostream>
using namespace std;
#include<string>
struct Student
{
string name;
int age;
int score;
};
int main(){
struct Student s={"张三",18,100};
Student*p=&s;
cout<<"姓名"<<p->name<<"年龄"<<p->age<<"分数"<<p->score<<endl;
return 0;
}
结构体嵌套结构体
#include<iostream>
using namespace std;
#include<string>
struct Student
{
string name;
int age;
int score;
};
struct teacher
{
int id;
string name;
int age;
struct Student s;
};
int main(){
teacher t;
t.id=122222;
t.name="老王";
t.age=30;
t.s.name="小王";
t.s.age=18;
t.s.score=80;
cout<<"老师姓名"<<t.name<<" 老师编号:"<<t.id<<" 老师年龄:" <<t.age<<" 老师学生名字:"<<t.s.name<<" 学生年龄:"<<t.s.age<<" 学生成绩:"<<t.s.score<<endl;
return 0;
}
结构体做函数参数
#include<iostream>
using namespace std;
#include<string>
struct Student
{
string name;
int age;
int score;
};
void printstudent(struct Student s)
{
s.age=120;
cout<<"函数中打印学生名字:"<<s.name<<" 学生年龄:"<<s.age<<" 学生成绩:"<<s.score<<endl;
}
void printstudent2(struct Student*p)
{
p->score=100;
cout<<"函数中打印学生名字:"<<p->name<<" 学生年龄:"<<p->age<<" 学生成绩:"<<p->score<<endl;
}
int main(){
Student s;
s.name="小王";
s.age=18;
s.score=80;
printstudent(s);
printstudent2(&s);
cout<<"函数中打印学生名字:"<<s.name<<" 学生年龄:"<<s.age<<" 学生成绩:"<<s.score<<endl;
return 0;
}
const使用场景
#include<iostream>
using namespace std;
#include<string>
struct Student
{
string name;
int age;
int score;
};
void printstudent(const Student*s)
{
cout<<"函数中打印学生名字:"<<s->name<<" 学生年龄:"<<s->age<<" 学生成绩:"<<s->score<<endl;
}
int main(){
Student s;
s.name="小王";
s.age=18;
s.score=80;
printstudent(&s);
return 0;
}