一、结构体定义
结构体属于用户自定义的类型,允许用户存储不同的数据类型。
语法:struct 结构体名{结构体成员列表};
通过结构体创建变量有三种方式:
- struct 结构体名 变量名
- struct 结构体名 变量名={成员1值,成员2值...}
- 定义结构体时顺便创建变量
一般使用前两种,因为第三种在定义时创建的变量容易被人所忽略。
#include <iostream> using namespace std; struct Student { string name; int age; float score; }s3; main() { //创建的时候struct关键字可以省略 Student s1; s1.name = "tom"; s1.age = 12; s1.score = 99; cout << name:" << s1.name << age:" << s1.age << score:" << s1.score << endl; struct Student s2 ={jack",15,1)">98}; s3.name = bob; s3.age = 19; s3.score = 97; system(pause); return 0; }
二、结构体数组
作用:将自定义的结构体放入到数组中方便维护。
语法:struct 结构体名 数组名[元素个数] = {{},{},...{}}
#include <iostream> score; }; 结构体数组定义 struct Student stuArr[3] { { 19,1)">},{ 22,1)"> },}; 可以修改值或者在这里进行赋值 stuArr[2].name = mike; 获取数组的长度 int length = sizeof(stuArr) / sizeof(stuArr[]); 遍历数组 for (int i = 0; i < length; i++) { cout << stuArr[i].name << stuArr[i].age << stuArr[i].score << endl; } system(三、结构体指针作用:通过指针来访问结构体中的成员
#include <iostream> struct Student s = { 12,1)"> }; Student* p = &s; 需要使用->来访问 cout << p->name << p->age << p->score << endl; system(四、结构体嵌套结构体#include <iostream> std; score; }; Teacher { id; age; Student stu; }; main() { Teacher t; t.id = 1; t.name = joke; t.age = 45struct Student stu = { }; t.stu = stu; cout << t.id << t.name << t.age << t.stu.name << t.stu.age << t.stu.score <<五。结构体做函数参数作用:将结构体作为参数向函数传递。
传递方式有两种:值传递、引用传递。
值传递:
#include <iostream> 值传递 void printStudent(Student stu) { stu.name = ; stu.age = 22; stu.score = 90结构体中的stu信息:" << endl; cout << stu.name << ," << stu.age << " << stu.score << endl; } }; cout << 未传入函数之前的结构体值: endl; printStudent(stu); cout << 传入函数之后的结构体值:" << stu.score<<; }输出:
引用传递:
#include <iostream> void printStudent(Student* stu) { stu->name = ; stu->age = ; stu->score = endl; cout << stu->name << " << stu->age << " << stu->score << }; struct Student* p = &stu; cout << endl; printStudent(p); cout << ; }输出:
六、结构体中const的使用场景
作用:用const防止误操作
#include <iostream> void printStudent(const Student* stu) { /*这里就不能进行修改了 stu->name = "jack"; stu->age = 22; stu->score = 90; */ cout << ; }输出:
只需要记住,用const修饰的数据类型就不能再进行更改。
相关文章
文章浏览阅读315次。之前用C语言编过链表,这几天突然想用C+...
文章浏览阅读219次。碰到问题就要记录下来,防止遗忘吧。文章...
文章浏览阅读1.8k次,点赞11次,收藏37次。因为自己对决策树...
文章浏览阅读492次。C++ 设计模式之策略模式
文章浏览阅读683次。我也算是个C++的小白,对于C++中的谓语我...
文章浏览阅读225次。又看了一遍操作符的东西,感觉之前对操作...