1.定义方法
第一种
#include<iostream>
#include<cstring>
using namespace std;
struct student
{
string name;
int age;
int score;
}s;
第二种
#include<iostream>
#include<cstring>
using namespace std;
struct student
{
string name;
int age;
int score;
}s;
第二种
int main()
{
struct student s;//c++中struct可省略
s.name="张三";
s.age=18;
s.score=100;
return 0;
}
第三种
#include<iostream>
#include<cstring>
using namespace std;
struct student
{
string name;
int age;
int score;
};
int main()
{
struct student s={"张三",18,100};//c++中struct可省略
return 0;
}
2.结构体数组
#include<iostream>
#include<cstring>
using namespace std;
struct student
{
string name;
int age;
int score;
};
int main()
{
struct student stu[3]=
{
{"张三",18,100},
{"李四",19,99},
{"王五",20,66}
};
for(int i=0;i<3;i++)
{
cout<<stu[i].name<<" "<<stu[i].age<<" "<<stu[i].score<<"\n";
}
return 0;
}
3.结构体指针
->为结构体指针访问元素的途径
#include<iostream>
#include<cstring>
using namespace std;
struct student
{
string name;
int age;
int score;
};
int main()
{
struct student s={"张三",18,100};
struct student * p=&s;
p->name="李四";
cout<<s.name<<"\n";
return 0;
}
4.结构体嵌套结构体
结构体可发生多层嵌套(在这里不过多演示,非常简单)
5.结构体做函数参数
#include<iostream>
#include<cstring>
using namespace std;
struct student
{
string name;
int age;
int score;
};
void print1(student s)
{
s.age=20;
}
void print2(student * s)
{
s->age=20;
}
int main()
{
struct student s={"张三",18,100};
//值传递
print1(s);
cout<<s.age<<"\n";
//址传递
print2(&s);
cout<<s.age<<"\n";
return 0;
}
6.结构体中const使用场景
#include<iostream>
#include<cstring>
using namespace std;
struct student
{
string name;
int age;
int score;
};
void print2(const student * s)//加const防止函数中的错误操作
{
//s->age=20;//操作失败,因为加了const修饰
cout<<s->age<<"\n";
}
int main()
{
struct student s={"张三",18,100};
print2(&s);
return 0;
}