本博文是学习黑马程序员C++视频时做的笔记,记录一下只是方便温故知新,不做其他用途。
一、结构体的定义和使用
结构体变量属于用户自定义数据类型,允许用户存储不同的数据类型。
#include<iostream>
using namespace std;
//1 创建学生数据类型 :
struct Student{
string name;
int age;
int score;
};
//2 通过学生类型创建具体学生
int main()
{
// 2.1 struct Student s1;
struct Student s1;
s1.name = "张三";
s1.age = 17;
s1.score = 95;
cout<<"姓名:"<<s1.name<<" 年龄:"<<s1.age<<" 分数:"<<s1.score<<endl;
// 2.2 struct Student s2;
struct Student s2 = {"李四",18,96};
cout<<"姓名:"<<s2.name<<" 年龄:"<<s2.age<<" 分数:"<<s2.score<<endl;
//2.3 在定义结构体变量时顺便创建结构体变量
struct Student1
{
string name;
int age;
int score;
}s3;
s3.name="王五";
s3.age=19;
s3.score=97;
cout<<"姓名:"<<s3.name<<" 年龄:"<<s3.age<<" 分数:"<<s3.score<<endl;
}
二、结构体和数组
作用:将自定义的结构体放入数组中方便维护
语法:struct 结构体 数组名[元素个数] = {{},{},…{}}
#include<iostream>
using namespace std;
//1 定义结构体
struct Student{
string name;
int age;
int score;
};
int main()
{
//2 创建结构体数组
struct Student stuarry[3]=
{
{"张三",17,95},
{"李四",18,96},
{"王五",19,97}
};
stuarry[0].name="陈十";
stuarry[0].age=26;
stuarry[0].score=100;
//3、结构体遍历
for(int i=0;i<3;i++)
{
cout<<"姓名:"<<stuarry[i].name<<" 年龄:"<<stuarry[i].age<<" 分数:"<<stuarry[i].score<<endl;
}
}
三、结构体和指针
作用:通过指针访问结构体中的成员
备注:利用操作符->可以通过结构体指针访问结构体属性
#include<iostream>
using namespace std;
struct Student{
string name;
int age;
int score;
};
int main()
{
//1 创建结构体变量
struct Student s1 = {"张三",17,95};
//2 通过指针指向结构体变量
struct Student *p = &s1;
//3 通过指针访问结构体变量当中的数据
cout<<"姓名:"<<p->name <<"年龄:" << p->age<<"成绩:" << p->score<<endl;
}
四、结构体的嵌套
#include<iostream>
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 = {"陈老师",12,56};
t.stu.name = "张三";
t.stu.age = 18;
t.stu.score = 95;
// 输出结构体的一些信息
cout<<t.name<<t.age<<t.stu.name<<t.stu.score<<endl;
}
五、结构体作为函数的参数
作用:结构体作为参数向函数传递
传递方式:值传递和地址传递
#include<iostream>
using namespace std;
struct Student{
string name;
int age;
int score;
};
//值传递函数
void PrintStudentValue(struct Student s)
{
cout<<"姓名:"<<s.name<<" 年龄"<<s.age<<" 分数"<<s.score<<endl;
}
//指针实现地址传递的函数
void PrintStudentAdress(struct Student *s)
{
cout<<"姓名:"<<s->name<<" 年龄"<<s->age<<" 分数"<<s->score<<endl;
}
int main()
{
// 学生结构体
struct Student s={"张三",19,95};
// 值传递函数调用
PrintStudentValue(s);
// 地址传递函数调用
PrintStudentAdress(&s);
}
六、结构体中const使用场景
作用:防止修改操作
#include<iostream>
using namespace std;
struct Student{
string name;
int age;
int score;
};
//指针实现地址传递的函数,可以节省内存空间,不会复制新的副本出来
void PrintStudentAdress(const Student *s)
{
// s->age = 55;//加了const ,修改内容,会报错
cout<<"姓名:"<<s->name<<" 年龄:"<<s->age<<" 分数:"<<s->score<<endl;
}
int main()
{
// 学生结构体
struct Student s={"张三",19,95};
// 地址传递
PrintStudentAdress(&s);
}