📦 C++ 结构体 - L29 数据结构

掌握struct的定义、数组、嵌套和与类的区别

📚 结构体概述

什么是结构体?

结构体(struct)是一种用户自定义的数据类型,它可以将不同类型的数据组合在一起,形成一个整体。结构体非常适合表示具有多个属性的实体。

  • 数据聚合:将相关数据组织在一起
  • 类型安全:编译器检查类型匹配
  • 代码清晰:提高程序可读性
  • 易于维护:集中管理相关数据
  • 广泛应用:学生信息、坐标点、日期等
💡 结构体 vs 类:
struct:默认成员是public,主要用于数据存储
class:默认成员是private,支持封装和方法
• 在C++中,struct可以包含函数,但通常用于简单数据集合

结构体的定义

#include <iostream> #include <string> using namespace std; // 定义结构体 struct Student { string name; // 姓名 int age; // 年龄 double score; // 成绩 string major; // 专业 }; int main() { // 创建结构体变量 Student stu1; stu1.name = "张三"; stu1.age = 18; stu1.score = 92.5; stu1.major = "计算机科学"; // 访问成员 cout << "姓名:" << stu1.name << endl; cout << "年龄:" << stu1.age << endl; cout << "成绩:" << stu1.score << endl; cout << "专业:" << stu1.major << endl; return 0; }

结构体初始化

#include <iostream> #include <string> using namespace std; struct Point { double x; double y; }; int main() { // 方法1:逐个赋值 Point p1; p1.x = 3.0; p1.y = 4.0; // 方法2:初始化列表 Point p2 = {1.0, 2.0}; // 方法3:C++11统一初始化 Point p3{5.0, 6.0}; // 方法4:指定成员初始化(C++20) Point p4 = {.x = 7.0, .y = 8.0}; cout << "p1: (" << p1.x << ", " << p1.y << ")" << endl; cout << "p2: (" << p2.x << ", " << p2.y << ")" << endl; cout << "p3: (" << p3.x << ", " << p3.y << ")" << endl; return 0; }

⚙️ 结构体数组

结构体数组的定义和使用

#include <iostream> #include <string> using namespace std; struct Student { string name; int age; double score; }; int main() { // 定义结构体数组 Student students[3]; // 输入学生信息 students[0] = {"张三", 18, 92.5}; students[1] = {"李四", 19, 88.0}; students[2] = {"王五", 20, 95.0}; // 遍历数组 for (int i = 0; i < 3; i++) { cout << "学生" << (i+1) << ":"; cout << students[i].name << ", "; cout << students[i].age << "岁, "; cout << "成绩:" << students[i].score << endl; } // 计算平均分 double total = 0; for (int i = 0; i < 3; i++) { total += students[i].score; } cout << "平均分:" << total / 3 << endl; return 0; }

动态结构体数组

#include <iostream> #include <vector> #include <string> using namespace std; struct Product { string name; double price; int quantity; }; int main() { // 使用vector实现动态数组 vector<Product> products; // 添加商品 products.push_back({"苹果", 5.5, 100}); products.push_back({"香蕉", 3.2, 150}); products.push_back({"橙子", 4.8, 80}); // 遍历显示 cout << "=== 商品清单 ===" << endl; for (const auto& product : products) { cout << product.name << ": "; cout << "¥" << product.price << " × "; cout << product.quantity << "个" << endl; } // 计算总价值 double totalValue = 0; for (const auto& product : products) { totalValue += product.price * product.quantity; } cout << "总价值:¥" << totalValue << endl; return 0; }
🎮 互动实验:结构体数组演示

输入学生数量,自动生成结构体数组代码

输入数量后点击按钮...

🛠️ 结构体嵌套

嵌套结构体的定义

#include <iostream> #include <string> using namespace std; // 定义日期结构体 struct Date { int year; int month; int day; }; // 定义学生结构体(嵌套Date) struct Student { string name; int age; Date birthDate; // 嵌套结构体 double score; }; int main() { Student stu; stu.name = "张三"; stu.age = 18; stu.birthDate.year = 2006; stu.birthDate.month = 5; stu.birthDate.day = 15; stu.score = 92.5; // 访问嵌套成员 cout << "姓名:" << stu.name << endl; cout << "生日:" << stu.birthDate.year << "-"; cout << stu.birthDate.month << "-"; cout << stu.birthDate.day << endl; return 0; }

复杂嵌套示例:地址信息

#include <iostream> #include <string> using namespace std; struct Address { string province; // 省 string city; // 市 string district; // 区 string street; // 街道 }; struct Contact { string phone; string email; }; struct Person { string name; int age; Address address; // 嵌套地址 Contact contact; // 嵌套联系方式 }; void printPerson(const Person& p) { cout << "=== 个人信息 ===" << endl; cout << "姓名:" << p.name << endl; cout << "年龄:" << p.age << endl; cout << "地址:" << p.address.province << p.address.city << p.address.district << p.address.street << endl; cout << "电话:" << p.contact.phone << endl; cout << "邮箱:" << p.contact.email << endl; } int main() { Person person; person.name = "李四"; person.age = 25; person.address = {"广东省", "深圳市", "南山区", "科技路1号"}; person.contact = {"13800138000", "lisi@example.com"}; printPerson(person); return 0; }

结构体作为函数参数

#include <iostream> #include <string> using namespace std; struct Rectangle { double width; double height; }; // 传值(拷贝整个结构体) double calculateArea(Rectangle rect) { return rect.width * rect.height; } // 传引用(更高效,不拷贝) void scaleRectangle(Rectangle& rect, double factor) { rect.width *= factor; rect.height *= factor; } // const引用(只读,防止修改) void printRectangle(const Rectangle& rect) { cout << "矩形:" << rect.width << "x" << rect.height << endl; cout << "面积:" << calculateArea(rect) << endl; } int main() { Rectangle rect = {5.0, 3.0}; printRectangle(rect); // 放大2倍 scaleRectangle(rect, 2.0); printRectangle(rect); return 0; }

🚀 结构体与类的区别

主要区别对比

// 结构体:默认public struct MyStruct { int x; // 默认public,外部可直接访问 void show() { // 可以有成员函数 cout << x << endl; } }; // 类:默认private class MyClass { int x; // 默认private,外部不能直接访问 public: void setX(int val) { x = val; } // 需要getter/setter int getX() { return x; } void show() { cout << x << endl; } }; int main() { MyStruct s; s.x = 10; // ✅ 可以直接访问 s.show(); MyClass c; // c.x = 10; // ❌ 编译错误,x是private c.setX(10); // ✅ 通过setter设置 c.show(); return 0; }
💡 选择建议:
使用struct:简单的数据集合,不需要封装
使用class:需要封装、继承、多态等OOP特性
实际开发:大多数情况使用class更规范

实际应用:学生管理系统

#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; struct Student { string name; int id; double score; }; // 比较函数(按成绩降序) bool compareByScore(const Student& a, const Student& b) { return a.score > b.score; } // 查找学生 int findStudent(const vector<Student>& students, int id) { for (size_t i = 0; i < students.size(); i++) { if (students[i].id == id) { return i; } } return -1; // 未找到 } int main() { vector<Student> students = { {"张三", 1001, 92.5}, {"李四", 1002, 88.0}, {"王五", 1003, 95.0} }; // 按成绩排序 sort(students.begin(), students.end(), compareByScore); cout << "=== 成绩排名 ===" << endl; for (size_t i = 0; i < students.size(); i++) { cout << (i+1) << ". "; cout << students[i].name << " (ID:"; cout << students[i].id << ") - "; cout << students[i].score << "分" << endl; } // 查找学生 int index = findStudent(students, 1002); if (index != -1) { cout << "\n找到学生:" << students[index].name << endl; } return 0; }

📝 实战练习

📝 理解测试

以下代码的输出是什么?

#include <iostream> using namespace std; struct Point { int x; int y; }; void modify(Point p) { p.x = 100; p.y = 200; } int main() { Point pt = {1, 2}; modify(pt); cout << pt.x << "," << pt.y << endl; return 0; }
选择答案查看解析...
💻 综合挑战

题目:设计一个Book(图书)结构体系统:
1. 定义Book结构体:书名、作者、价格、ISBN
2. 创建图书数组(至少3本书)
3. 实现功能:查找最贵的书、计算平均价格、按价格排序
4. 输出所有图书信息和统计结果

点击"生成代码框架"查看提示...