当前位置: 首页 > news >正文

第7天:结构体与联合体 - 复杂数据类型

第7天:结构体与联合体 - 复杂数据类型

一、📚 今日学习目标

  1. 🎯 掌握结构体(struct)的定义与使用
  2. 🔧 理解联合体(union)的特性与适用场景
  3. 💡 完成图书馆管理系统实战(结构体数组操作)
  4. 🛠️ 学会使用typedef简化类型定义

二、⚙️ 核心知识点详解

1. 结构体(Struct)

定义与初始化
// 定义结构体
struct Book {string title;string author;int publicationYear;double price;
};// 初始化方式
Book book1 = {"C++ Primer", "Stanley B. Lippman", 2012, 129.99};
Book book2{"Effective C++", "Scott Meyers", 2005}; // 自动填充默认值
成员函数
struct Circle {double radius;double area() const { // 常成员函数return 3.14159 * radius * radius;}
};Circle c;
cout << "圆的面积:" << c.area() << endl;

2. 联合体(Union)

定义与内存分配
union DateTime {int timestamp; // 秒级时间戳struct {int year;int month;int day;} date;
};// 联合体所有成员共享同一块内存
DateTime dt;
dt.timestamp = 1672531200; // 2023-01-01 00:00:00
cout << "日期:" << dt.date.year << "-" << dt.date.month << "-" << dt.date.day << endl;

3. 类型别名(typedef)

简化复杂类型
typedef pair<string, int> StudentID; // C++标准库类型
typedef vector<pair<string, double>> StockPortfolio;StudentID sid = {"S12345", 2023};
StockPortfolio portfolio = {{"AAPL", 185.5}, {"GOOGL", 2780.3}};

三、🔧 代码实战:图书馆管理系统

1. 功能需求

  • 录入图书信息(书名/作者/ISBN/价格)
  • 查询图书是否存在
  • 删除指定图书
  • 显示所有图书信息

2. 实现步骤

#include <iostream>
#include <vector>
#include <string>
using namespace std;struct LibraryBook {string isbn;string title;string author;double price;bool operator<(const LibraryBook& other) const {return isbn < other.isbn; // 按ISBN排序}
};int main() {vector<LibraryBook> books;const int MAX_BOOKS = 100;while (books.size() < MAX_BOOKS) {LibraryBook book;cout << "请输入图书ISBN(输入q退出):";cin >> book.isbn;if (book.isbn == "q") break;cin.ignore(numeric_limits<streamsize>::max(), '\n');getline(cin, book.title);getline(cin, book.author);cout << "请输入价格:";cin >> book.price;books.push_back(book);}// 查询功能string queryIsbn;cout << "\n🔍 查询图书(输入q退出):" << endl;while (cin >> queryIsbn && queryIsbn != "q") {bool found = false;for (const auto& book : books) {if (book.isbn == queryIsbn) {cout << "📖 图书信息:" << endl;cout << "ISBN: " << book.isbn << endl;cout << "书名: " << book.title << endl;cout << "作者: " << book.author << endl;cout << "价格: $" << book.price << endl;found = true;break;}}if (!found) {cout << "📝 未找到该图书!" << endl;}}return 0;
}

四、🛠️ 进阶技巧

1. 结构体数组排序

vector<Student> students = {...};
sort(students.begin(), students.end(), [](const Student& a, const Student& b) {return a.score > b.score; // 按成绩降序排列
});

2. 联合体在位操作中的应用

union Byte {unsigned char uc;int i;
};Byte b;
b.uc = 0xAA; // 二进制10101010
cout << "十六进制表示:" << hex << b.i << endl; // 输出0xaa

3. 匿名结构体

struct {int x;int y;
} point = {10, 20}; // 直接使用无需typedef

五、❓ 常见问题解答

Q:结构体和类有什么区别?​
→ 结构体默认public访问权限,类默认private;结构体通常用于数据聚合,类强调封装和继承

Q:联合体如何保证数据完整性?​
→ 需要手动记录当前存储的是哪种类型的数据
Q:typedef和using有什么区别​?
→ C++中using可以替代typedef的所有功能,还支持模板参数推导


六、📝 今日总结

✅ 成功掌握:

  • 📚 结构体的定义与成员函数
  • 💡 联合体的内存共享特性
  • 🔄 图书馆管理系统的完整实现
  • 🔧 类型别名的灵活运用

⏳ 明日预告:

  • 面向对象编程入门(类与对象/封装/继承)

七、📝 课后挑战任务

1. 🌟 扩展图书馆系统:

  • 添加借阅功能(记录借阅人信息)
  • 实现按价格区间筛选图书

2.🔍 联合体应用:

// 完成时间格式转换程序
union Time {int totalSeconds;struct {int hours;int minutes;int seconds;};
};Time t;
t.totalSeconds = 3661;
cout << "时间表示:" << t.hours << "小时"<< t.minutes << "分钟" << t.seconds << "秒" << endl;

3. 📝 技术总结:

  • 绘制结构体与联合体的内存对比图
  • 列举5个典型结构体应用场景(如Point/Rectangle/Student等

🔍 上一天课后挑战任务答案

任务1:改进学生管理系统(带等级判定和姓名查询)

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
using namespace std;struct Student {string name;double score;char grade; // 新增等级字段
};// 计算等级的辅助函数
char calculateGrade(double score) {if (score >= 90) return 'A';else if (score >= 80) return 'B';else if (score >= 70) return 'C';else if (score >= 60) return 'D';else return 'F';
}int main() {const int N = 5;vector<Student> students(N);// 录入学生信息并计算等级for (int i = 0; i < N; ++i) {cin >> students[i].name >> students[i].score;students[i].grade = calculateGrade(students[i].score);}// 按姓名查询成绩string queryName;cout << "\n🔍 按姓名查询成绩:" << endl;cin >> queryName;bool found = false;for (const auto& s : students) {if (s.name == queryName) {cout << "姓名:" << s.name << " | 成绩:" << s.score << " | 等级:" << s.grade << endl;found = true;break;}}if (!found) {cout << "📝 未找到该学生的记录!" << endl;}// 输出完整信息(含等级)cout << "\n📊 学生成绩单:" << endl;for (const auto& s : students) {cout << setw(10) << left << s.name << setw(8) << right << s.score << setw(4) << right << s.grade << endl;}return 0;
}

任务2:指针迷宫修正

原错误代码
int arr[] = {1,2,3,4,5};
void update(int* p) {p = new int[10];for (int i=0; i<10; i++) {p[i] = i*10;}
}
int main() {int* p = arr;update(p);cout << *p << endl;return 0;
}

错误分析

  • 函数update内部重新绑定了指针p,但并未修改原始指针的值
  • main函数的p仍然指向原数组,未指向新分配的内存

修正版本

#include <iostream>
using namespace std;void update(int*& p) { // 传递指针的引用p = new int[10];for (int i=0; i<10; i++) {p[i] = i*10;}
}int main() {int arr[] = {1,2,3,4,5};int* p = arr;update(p); // 传递指针的引用cout << *p << endl; // 输出10delete[] p; // 释放内存return 0;
}

任务3:技术总结

指针与内存地址关系示意图
假设存在以下指针操作:
int num = 42;
int* p = &num;
int**​ pp = &p;内存布局:
+--------+-------+------+
|  num   |  p    |  pp  |
+--------+-------+------+
|  42    | 0x100 | 0x200|
+--------+-------+------+
地址:  0x100  0x200  0x300
常见内存错误类型
错误类型现象预防方法
内存泄漏程序占用内存持续增长使用智能指针/delete及时释放
野指针访问未初始化或失效内存初始化指针为nullptr
越界访问数组/指针越界严格检查下标范围
内存重复释放运行时崩溃为每个new分配唯一delete
http://www.lryc.cn/news/543937.html

相关文章:

  • vue富文本 vue-quill-editor + 上传图片到阿里云服务器 + 修改富文本内容
  • Java常见设计模式(中):结构型模式
  • DeepSeek R1 + 飞书机器人实现AI智能助手
  • 【论文详解】Transformer 论文《Attention Is All You Need》能够并行计算的原因
  • 51c嵌入式~电路~合集12
  • php 获取head参数
  • 蓝桥杯嵌入式备赛
  • 基于PyTorch实现的自适应注意力卷积网络(AACN)详解
  • 基于Javase的停车场收费管理系统
  • Cookie与Session:Web开发中的状态管理机制
  • python量化交易——金融数据管理最佳实践——qteasy创建本地数据源
  • 手机放兜里,支付宝“碰一下”被盗刷?
  • C/C++语言知识点一
  • 前端面试题---在vue中为什么要用路由
  • Three.js 快速入门教程【十】常见的纹理类型
  • 文档识别-C#中英文文档识别接口-PDF文件内容识别API
  • gRPG协议
  • 【maven打包错误】 无效的目标发行版:16
  • Oracle 查询表空间使用情况及收缩数据文件
  • Transformer 代码剖析1 - 数据处理 (pytorch实现)
  • Python异常处理面试题及参考答案
  • Python多线程知多少
  • C++ Qt常见面试题(8):C++ Qt中的线程同步与互斥
  • 数字内容个性化推荐的关键是什么?
  • DeepSeek-OpenSourceWeek-第三天-Release of DeepGEMM
  • LeetCode 1472.设计浏览器历史记录:一个数组完成模拟,单次操作均O(1)
  • AI+游戏,正在进行时!
  • 贪心算法精品题
  • sql server 复制从备份初始化数据
  • 【蓝桥杯】1.k倍区间