基本概念
- 结构体属于用户 自定义的数据类型 , 允许用户存储不同的数据类型
结构体定义 , 使用
- 语法
- struct 结构体名 = { 结构体成员列表 };
- 通过结构体创建变量的方式有三种; 使用
- struct 结构体名 变量名
- struct 结构体名 变量名 = { 成员1值 , 成员2值 }
- 定义结构体时 , 顺便创建变量
//定义结构体 struct Student{ //成员列表
string name; //学生姓名int age; //学生年龄double score; //学生分数
};
//通过结构体创建具体的事务 struct Student s1 = {“李四”,20,60.5};
int main() { s1.name = “张三”; s1.age = 19; s1.score = 61.5;
printf("姓名: %s 年龄: %d; 分数: %f", &s1.name, s1.age, s1.score);return 0;
}
---<a name="zMMsU"></a>### 结构体数组1. 语法- struct 结构体名 数组名[元素个数] = { { } , { } }2. 示例```cpp#include <iostream>using namespace std;//定义结构体struct Student {string name; //姓名int age; //年龄};int main() {struct Student stuArray[3] = {{"王麻子",18},{"李四",19},{"王五",20}};for (int i = 0; i < 3; i++){printf("姓名:%s , 年龄:%d \n", stuArray[i].name, stuArray[i].age);}return 0;}
结构体指针
#include <iostream>using namespace std;#include <string>//定义结构体struct Student {string name;int age;};int main() {//创建结构体struct Student s = { "王麻子",18 };//指针Student* p = &s;//初始化printf("姓名:%s , 年龄:%d", p->name, p->age);return 0;}
结构体嵌套
#include <iostream>
using namespace std;
#include <string>
struct Student {
string name;
int age;
};
struct Teacher {
int id;
string name;
int age;
struct Student stu;
};
int main() {
struct Teacher t;
t.id = 1001;
t.name = "王老师";
t.age = 30;
t.stu.name = "王同学";
t.stu.age = 18;
printf("老师编号:%d \n 老师姓名:%s \n 老师年龄:%d\n",t.id,t.name,t.age);
printf("------------------------\n%s","");
printf("学生姓名:%s\n 学生年龄:%d", t.stu.name, t.stu.age);
return 0;
}
include
struct Student { string name;
int age;
};
void viewStudent(const Student stu) {
//stu.name = "asd"; 错误;加了const 就不能修改
printf("学生姓名: %s \n 学生年龄: %d",stu.name,stu.age);
}
void viewStudent2(const Student * stu) {
//stu->name = "asd"; 错误;加了const 就不能修改
printf("学生姓名: %s \n 学生年龄: %d",stu->name,stu->age);
}
int main() { struct Student stu = {“王麻子”,18};
viewStudent(stu);
return 0;
} ```
