pc网站运营,山东建设住建厅网站,e龙岩官网12345,哈尔滨做网站的公司哪家好第7天#xff1a;结构体与联合体 - 复杂数据类型
一、#x1f4da; 今日学习目标
#x1f3af; 掌握结构体#xff08;struct#xff09;的定义与使用#x1f527; 理解联合体#xff08;union#xff09;的特性与适用场景#x1f4a1; 完成图书馆管理系统实战…第7天结构体与联合体 - 复杂数据类型
一、 今日学习目标 掌握结构体struct的定义与使用 理解联合体union的特性与适用场景 完成图书馆管理系统实战结构体数组操作️ 学会使用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 pairstring, int StudentID; // C标准库类型
typedef vectorpairstring, 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() {vectorLibraryBook 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_limitsstreamsize::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. 结构体数组排序
vectorStudent 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; // 输出0xaa3. 匿名结构体
struct {int x;int y;
} point {10, 20}; // 直接使用无需typedef五、❓ 常见问题解答
Q结构体和类有什么区别? → 结构体默认public访问权限类默认private结构体通常用于数据聚合类强调封装和继承
Q联合体如何保证数据完整性 → 需要手动记录当前存储的是哪种类型的数据 Qtypedef和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;vectorStudent 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 i0; i10; 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 i0; i10; 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