目录
结构体的定义和使用
struct 结构体名{结构体成员列表};
上面我们设置好了一个结构体之后,然后我们可以创建结构体变量
一共有三种创建的方式
(1)struct 结构体名 变量名;
(2)struct 结构体名 变量名 = {成员1,成员2};
(3)定义结构体的时候顺便创建变量
#include <iostream>
#include<string>
using namespace std;
//1.创建学生结构体类型:学生(姓名,年龄,分数)
struct Student {
string name;
int age;
int score;
}s3;
int main()
{
//(1)struct Student s1;
struct Student s1;//struct的关键字可以不写
//给s1赋值,通过一个.来访问结构体变量的属性
s1.name = "张三";
s1.age = 18;
s1.score = 100;
//(2)struct Student s2={....}
struct Student s2 = { "李四",19,80 };//struct的关键字可以不写
//定义结构体的时候顺便就创建
s3.name = "王五";
s3.age = 19;
s3.score = 10;
return 0;
}
结构体数组
语法:struct 结构体名 数组名[元素个数] = {{} ,{}, {},{}};
#include <iostream>
#include<string>
using namespace std;
//1.创建学生结构体类型:学生(姓名,年龄,分数)
struct Student {
string name;
int age;
int score;
};
int main()
{
struct Student stuArray[3] =
{
{"张三",18,100},
{"李四",29,100},
{"王五",8,99}
};
//改变数据
stuArray[2].name = "赵六";
stuArray[2].age = 80;
//遍历结构体数组
for (int i = 0; i < 3; i++)
{
cout << "姓名 " << stuArray[i].name<<endl;
}
return 0;
}
结构体指针
#include <iostream>
#include<string>
using namespace std;
//1.创建学生结构体类型:学生(姓名,年龄,分数)
struct Student {
string name;
int age;
int score;
};
int main()
{
//1.创建一个结构体变量
Student s = { "张三",18,100 };
//2.通过指针指向结构体变量
Student* p = &s;
//3.通过指针访问结构体变量中的数据,用-->来访问属性
cout << p->name << endl;
return 0;
}
结构体传参
#include <iostream>
#include<string>
using namespace std;
//1.创建学生结构体类型:学生(姓名,年龄,分数)
struct Student {
string name;
int age;
int score;
};
void printStudent1(Student s)
{
s.name = 100;
cout << s.name << s.age << s.score << endl;
}
void printStudent2(Student* s)
{
s->age = 200;
cout << s->age << endl;
}
int main()
{
//1.创建一个结构体变量
Student s = { "张三",18,100 };
printStudent1(s);//值传递不能改变结构体中的值
printStudent2(&s);//地址传递可以改变结构体中的值
return 0;
}