目录
语法:
struct 结构体名{
结构体成员列表
};
2.1 创建学生数据类型
struct Student{
string name; //姓名
int age; //年龄
int score; //分数
};
2.2 通过学生类型创建具体学生
(创建时struct 关键字可以省略,定义时不能)
struct Student S1; //Student S1 也可
S1.name = "张三";
S1.age = 18;
S1.score = 100;
struct Student S2 = {"李四",19,80};
//定义结构体时顺便创建结构变量
struct Student{
string name; //姓名
int age; //年龄
int score; //分数
}S3; //顺便创建结构体变量,S3就是结构体变量
S3.name = "张三";
S3.age = 18;
S3.score = 100;
2.3 结构体数组
语法: struct 结构体名 数组名{元素个数}={{},{},...{}}
//1.定义结构体
struct Student{
string name; //姓名
int age; //年龄
int score; //分数
};
int main(){
//2.创建结构体数组
struct Student stuArray[3] = {
{"张三",18,100},
{"李四",28,99},
{"王五",38,166},
};
//3.给结构体数组中的元素赋值
stuArray[2].name = "赵六";
//4.遍历结构体数组
for(int i = 0 ; i < 3 ; i++)
{
cout <<"姓名:"<<stuArray[i].name
<<"年龄:"<<stuArray[i].age
<<"成绩:"<<stuArray[i].score<<endl;
}
}
2.4 结构体指针
利用操作符->可以通过结构体指针访问结构体属性
//1.定义结构体
struct Student{
string name; //姓名
int age; //年龄
int score; //分数
};
int main(){
//1.创建学生结构体变量
struct Student s = {"张三",18,100}; //struct可省略
//2.通过指针指向结构体变量
struct Student * p = &a; //struct可省略
//3.通过指针访问结构体变量中的数据
cout<<"姓名:"<< p->name <<"年龄:"<< p->age <<"成绩:"<< p->score;
}
2.5 结构体嵌套结构体
#include<iostream>
#include<string>
using namespace std;
//学生结构体
struct student {
string name;
int age;
int score;
};
//老师结构体
struct teacher {
int id;
string name;
int age;
struct student stu; //辅导的学生
};
int main()
{
teacher t;
t.age = 50;
t.id = 10000;
t.name = "老王";
t.stu.name = "小王";
t.stu.age = 18;
t.stu.score = 100;
cout << "老师姓名:" << t.name<<endl << "学生姓名:" << t.stu.name<<endl;
system("pause");
return 0;
}
2.6 结构体做函数参数
#include<iostream>
#include<string>
using namespace std;
//学生结构体
struct student {
string name;
int age;
int score;
};
void printstudent1(struct student s)// 值传递
{
cout << "子函数1中 姓名:" << s.name << endl;
}
void printstudent2(struct student* p)//地址传递
{
cout << "子函数2中 姓名:" << p->name << endl;
}
int main()
{
student s;
s.name = "张三";
s.age = 20;
s.score = 85;
printstudent1(s);
printstudent2(&s);
return 0;
}
2.7 结构体中const使用
void print(const student *p ) //p的值无法被修改,类似实参形参,不过指针只传递地址,参数要传输大量数据,节省了空间.加入const之后一旦有修改操作就会报错