基本概念

  • 结构体属于用户 自定义的数据类型 , 允许用户存储不同的数据类型

结构体定义 , 使用

  1. 语法
  • struct 结构体名 = { 结构体成员列表 };
  1. 通过结构体创建变量的方式有三种; 使用
  • struct 结构体名 变量名
  • struct 结构体名 变量名 = { 成员1值 , 成员2值 }
  • 定义结构体时 , 顺便创建变量
  1. 示例 ```c

    include

    using namespace std;

//定义结构体 struct Student{ //成员列表

  1. string name; //学生姓名
  2. int age; //学生年龄
  3. double score; //学生分数

};

//通过结构体创建具体的事务 struct Student s1 = {“李四”,20,60.5};

int main() { s1.name = “张三”; s1.age = 19; s1.score = 61.5;

  1. printf("姓名: %s 年龄: %d; 分数: %f", &s1.name, s1.age, s1.score);
  2. return 0;

}

  1. ---
  2. <a name="zMMsU"></a>
  3. ### 结构体数组
  4. 1. 语法
  5. - struct 结构体名 数组名[元素个数] = { { } , { } }
  6. 2. 示例
  7. ```cpp
  8. #include <iostream>
  9. using namespace std;
  10. //定义结构体
  11. struct Student {
  12. string name; //姓名
  13. int age; //年龄
  14. };
  15. int main() {
  16. struct Student stuArray[3] = {{"王麻子",18},{"李四",19},{"王五",20}};
  17. for (int i = 0; i < 3; i++){
  18. printf("姓名:%s , 年龄:%d \n", stuArray[i].name, stuArray[i].age);
  19. }
  20. return 0;
  21. }

结构体指针

  1. #include <iostream>
  2. using namespace std;
  3. #include <string>
  4. //定义结构体
  5. struct Student {
  6. string name;
  7. int age;
  8. };
  9. int main() {
  10. //创建结构体
  11. struct Student s = { "王麻子",18 };
  12. //指针
  13. Student* p = &s;
  14. //初始化
  15. printf("姓名:%s , 年龄:%d", p->name, p->age);
  16. return 0;
  17. }

结构体嵌套

#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;
}

  • 结构体也可以作为参数进行传递
  • 也可以通过 const 控制 作为参数的结构体不能被修改 ```cpp

    include

    using namespace std;

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;

} ```