seo网站买seo营销网站的设计标准
第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 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 = #
int** pp = &p;内存布局:
+--------+-------+------+
| num | p | pp |
+--------+-------+------+
| 42 | 0x100 | 0x200|
+--------+-------+------+
地址: 0x100 0x200 0x300
常见内存错误类型
错误类型 | 现象 | 预防方法 |
---|---|---|
内存泄漏 | 程序占用内存持续增长 | 使用智能指针/delete及时释放 |
野指针 | 访问未初始化或失效内存 | 初始化指针为nullptr |
越界访问 | 数组/指针越界 | 严格检查下标范围 |
内存重复释放 | 运行时崩溃 | 为每个new分配唯一delete |