实验3
任务1:
源代码:
button.hpp
#pragma once #include <iostream> #include <string> class Button { public: Button(const std::string &label); const std::string& get_label() const; void click(); private: std::string label_; }; inline Button::Button(const std::string &label): label_{label} { } inline const std::string& Button::get_label() const { return label_; } inline void Button::click() { std::cout << "Button '" << label_ << "' clicked\n"; }
window.hpp
#pragma once #include "button.hpp" #include <iostream> #include <vector> #include <algorithm> // 窗口类 class Window{ public: Window(const std::string &title); void display() const; void close(); void add_button(const std::string &label); void click_button(const std::string &label); private: bool has_button(const std::string &label) const; std::string title_; std::vector<Button> buttons_; }; inline Window::Window(const std::string &title): title_{title} { buttons_.push_back(Button("close")); } inline void Window::display() const { std::string s(40, '*'); std::cout << s << std::endl; std::cout << "window : " << title_ << std::endl; int cnt = 0; for(const auto &button: buttons_) std::cout << ++cnt << ". " << button.get_label() << std::endl; std::cout << s << std::endl; } inline void Window::close() { std::cout << "close window '" << title_ << "'" << std::endl; click_button("close"); } inline bool Window::has_button(const std::string &label) const { for(const auto &button: buttons_) if(button.get_label() == label) return true; return false; } inline void Window::add_button(const std::string &label) { if(has_button(label)) std::cout << "button " << label << " already exists!\n"; else buttons_.push_back(Button(label)); } inline void Window::click_button(const std::string &label) { for(auto &button:buttons_) if(button.get_label() == label) { button.click(); return; } std::cout << "no button: " << label << std::endl; }
task1.cpp
#include "window.hpp" #include <iostream> void test(){ Window w("Demo"); w.add_button("add"); w.add_button("remove"); w.add_button("modify"); w.add_button("add"); w.display(); w.close(); } int main() { std::cout << "用组合类模拟简单GUI:\n"; test(); return 0; }
运行结果截图:

问题 1:
是组合关系。buttons_ 是 std::vector<Button>,按值持有 Button,由 Window 构造和 add_button() 创建;Window 析构时 vector 会自动析构所有按钮,无需手动 delete,也没有外部共享,因此生命周期由 Window 统一管理。
问题 2:
改为 public 的优点是外部可直接查询按钮是否存在、便于测试和界面状态判断;风险是扩大接口承诺、暴露内部容器,未来更换容器也要维持该行为。设计时应把使用者需要且稳定的操作设为 public,把仅内部使用、暴露实现细节或可能破坏不变量的函数设为 private,因此 has_button() 作为内部辅助更适合 private。
问题 3:
接口 1 返回 const 引用,不复制、O(1),但不能修改且引用可能随对象销毁而悬空;接口 2 返回副本,O(n) 且可能分配内存,但返回值独立、生命周期安全、调用者可修改副本。按钮标签这种短生命周期只读场景适合接口 1,需要长期保存时用接口 2。
问题 4 ①:
可以正常运行,输出不变。push_back(Button(xxx)) 先构造临时 Button 再移动/复制进 vector;emplace_back(xxx) 把 xxx 作为构造参数在 vector 内存中直接构造,通常少一次临时对象和移动,但可读性和隐式转换控制稍弱。
问题 4 ②:
可以,window.hpp 已包含 <algorithm>。std::any_of(first, last, pred) 判断区间内是否存在满足谓词的元素,参数是首尾迭代器和一元谓词,返回 bool,找到即提前结束。
问题 4 ③:
可以。std::find_if(first, last, pred) 返回第一个满足谓词元素的迭代器,找不到返回 last;参数同样是首尾迭代器和一元谓词。找到后执行 it->click(),否则输出 no button。
问题 5:
上百个按钮时线性查找 O(n) 通常还不算明显瓶颈,但点击极频繁时会变慢;std::map 可把查找降为 O(log n),但 display() 会按标签字典序输出,按钮顺序和编号改变,通常不可接受。可以保留 vector 维持顺序,另用 unordered_map 建“标签→下标”索引。
任务2:
源代码:
task2.cpp
#include <cstddef> #include <iostream> #include <vector> void test1(); void test2(); void output1(const std::vector<int> &v); void output2(const std::vector<int> &v); void output3(const std::vector<std::vector<int>>& v); int main() { std::cout << "深复制验证1: 标准库vector<int>\n"; test1(); std::cout << "\n深复制验证2: 标准库vector<int>嵌套使用\n"; test2(); return 0; } void test1() { std::vector<int> v1(5, 42); const std::vector<int> v2(v1); std::cout << "**********拷贝构造后**********\n"; std::cout << "v1: "; output1(v1); std::cout << "v2: "; output1(v2); v1[0] = -1; std::cout << "**********修改v1[0]后**********\n"; std::cout << "v1: "; output1(v1); std::cout << "v2: "; output1(v2); } void test2() { std::vector<std::vector<int>> v1{{1, 2, 3}, {4, 5, 6, 7}}; const std::vector<std::vector<int>> v2(v1); std::cout << "**********拷贝构造后**********\n"; std::cout << "v1:\n"; output3(v1); std::cout << "v2:\n"; output3(v2); v1[0].push_back(-1); std::cout << "**********修改v1[0]后**********\n"; std::cout << "v1:\n"; output3(v1); std::cout << "v2:\n"; output3(v2); } // 使用索引+循环,遍历输出vector<int>数据项 void output1(const std::vector<int> &v) { if(v.size() == 0) { std::cout << '\n'; return; } std::cout << v[0]; for(std::size_t i = 1; i < v.size(); ++i) std::cout << ", " << v[i]; std::cout << '\n'; } // 使用迭代器+循环,遍历输出vector<int>数据项 void output2(const std::vector<int> &v) { if(v.size() == 0) { std::cout << '\n'; return; } auto it = v.begin(); std::cout << *it; for(it = v.begin()+1; it != v.end(); ++it) std::cout << ", " << *it; std::cout << '\n'; } // 使用auto for分行输出vector<vector<int>>数据项 void output3(const std::vector<std::vector<int>>& v) { if(v.size() == 0) { std::cout << '\n'; return; } for(auto &i: v) output2(i); }
运行结果截图:

问题 1:v1(5, 42) 是“元素个数+初值”构造,生成 5 个值为 42 的元素;v2(v1) 是拷贝构造,也生成 5 个 42,且两者数据区独立。
问题 2:
初始化后 v1.size() = 2、v2.size() = 2、v1[0].size() = 3;执行 v1[0].push_back(-1) 后,v1[0].size() 变为 4。
问题 3:
合法下标时等价,都能修改元素;区别是 at() 会做边界检查,越界抛 std::out_of_range,operator[] 不检查,越界是未定义行为。
问题 4:
能输出 -1,因为 r 是 v1[0] 的 const 引用而不是副本,push_back 后其最后一个元素就是 -1,r.size() 为 4。const& 避免了整个内层 vector 的拷贝,但只能读,且原对象销毁或外层 vector 重新分配后 r 会悬空。
问题 5:
vector 的拷贝构造会为新对象分配独立缓冲区并复制元素,所以是深拷贝;嵌套 vector 也会递归复制内层。非 const 的 v.at(0) 返回 int&,const 的返回 const int&,因此需要成对提供 const/非 const 重载,才能既支持 const 对象只读访问,又允许非 const 对象修改。
vectorInt.hpp
#pragma once #include <iostream> #include <stdexcept> // 动态int数组对象类 class vectorInt{ public: vectorInt(); vectorInt(int n); vectorInt(int n, int value); vectorInt(const vectorInt &vi); ~vectorInt(); int size() const; int& at(int index); const int& at(int index) const; vectorInt& assign(const vectorInt &vi); int* begin(); int* end(); const int* begin() const; const int* end() const; private: int n_; // 当前数据项个数 int *pdata_; // 数据区 }; inline vectorInt::vectorInt():n_{0}, pdata_{nullptr} { } inline vectorInt::vectorInt(int n): n_{n}, pdata_{new int[n]} { } inline vectorInt::vectorInt(int n, int value): n_{n}, pdata_{new int[n]} { for(auto i = 0; i < n_; ++i) pdata_[i] = value; } inline vectorInt::vectorInt(const vectorInt &vi): n_{vi.n_}, pdata_{new int[n_]} { for(auto i = 0; i < n_; ++i) pdata_[i] = vi.pdata_[i]; } inline vectorInt::~vectorInt() { delete [] pdata_; } inline int vectorInt::size() const { return n_; } inline const int& vectorInt::at(int index) const { if(index < 0 || index >= n_) throw std::out_of_range("vectorInt::at: index out of range"); return pdata_[index]; } inline int& vectorInt::at(int index) { if(index < 0 || index >= n_) throw std::out_of_range("vectorInt::at: index out of range"); return pdata_[index]; } inline vectorInt& vectorInt::assign(const vectorInt &vi) { if(this == &vi) return *this; int *ptr; ptr = new int[vi.n_]; for(int i = 0; i < vi.n_; ++i) ptr[i] = vi.pdata_[i]; delete[] pdata_; n_ = vi.n_; pdata_ = ptr; return *this; } inline int* vectorInt::begin() { return pdata_; } inline int* vectorInt::end() { return pdata_ + n_; } inline const int* vectorInt::begin() const { return pdata_; } inline const int* vectorInt::end() const { return pdata_ + n_; }
task3.cpp
#include "vectorInt.hpp" #include <iostream> void test1(); void test2(); void test3(); void output1(const vectorInt &vi); void output2(const vectorInt &vi); int main() { std::cout << "测试1: 构造、更新\n"; test1(); std::cout << "\n测试2: const对象、赋值\n"; test2(); std::cout << "\n测试3: 赋值\n"; test3(); return 0; } void test1() { int n; std::cout << "Enter n: "; std::cin >> n; vectorInt x1(n); for(auto i = 0; i < n; ++i) x1.at(i) = (i+1)*10; std::cout << "x1: "; output1(x1); vectorInt x2(n, 42); vectorInt x3(x2); x2.at(0) = -1; std::cout << "x2: "; output1(x2); std::cout << "x3: "; output1(x3); } void test2() { const vectorInt x(5, 42); vectorInt y; y.assign(x); std::cout << "x: "; output2(x); std::cout << "y: "; output2(y); y.at(0) = -1; std::cout << "x: "; output2(x); std::cout << "y: "; output2(y); } void test3() { vectorInt x(5, 42); std::cout << "x: "; output2(x); x.assign(x); std::cout << "x: "; output2(x); } // 使用xx.at()+循环输出vectorInt对象数据项 void output1(const vectorInt &vi) { if(vi.size() == 0) { std::cout << '\n'; return; } std::cout << vi.at(0); for(auto i = 1; i < vi.size(); ++i) std::cout << ", " << vi.at(i); std::cout << '\n'; } // 使用迭代器+循环输出vectorInt对象数据项 void output2(const vectorInt &vi) { if(vi.size() == 0) { std::cout << '\n'; return; } auto it = vi.begin(); std::cout << *it; for(it = vi.begin()+1; it != vi.end(); ++it) std::cout << ", " << *it; std::cout << '\n'; }
运行结果截图:

问题 1:
版本 2 在自赋值 x.assign(x) 时先 delete[] pdata_,源数据被释放,随后 pdata_ 和 vi.pdata_ 指向同一块新内存,循环等于把未初始化内存赋给自己,输出会变成垃圾值或崩溃;普通运行也可能碰巧仍显示 42,但这是未定义行为。它还缺少自赋值保护,并且 new 失败时对象处于悬空状态,析构可能 double free,不满足异常安全。
问题 2:static_cast<const vectorInt*>(this) 把非 const 成员里的 vectorInt* 转成 const vectorInt*,以便调用 const 版 at(),避免递归并复用边界检查;const_cast<int&> 把 const 版返回的 const int& 转成 int&,让非 const 对象可以修改元素。非 const 成员只能由非 const 对象调用,所以这种去 const 修改是合法的。
问题 3:v1 非 const,v1.begin() 选非 const 重载,it1 为 int*;v2 是 const,只能选 const 重载,it2 为 const int*。前者适合读写,后者适合只读;原始指针作为迭代器也说明迭代器本质是“支持遍历操作的对象”,只是标准迭代器封装得更好、更安全。
问题 4:
可以,需包含 <algorithm>。fill_n 把前 n 个元素填成 value;copy_n(vi.pdata_, vi.n_, pdata_) 把源数据复制到已分配的目标;copy_n(vi.pdata_, vi.n_, ptr) 先复制到新缓冲区,再释放旧内存,分别等价于原来的三个循环。
#pragma once // 类Matrix声明 class Matrix { public: Matrix(int n_rows, int n_cols, double value = 0); // 构造n_rows*n_cols_矩阵对象, 初值value Matrix(int n_rows, double value = 0); // 构造n_rows*n_rows方阵对象, 初值value Matrix(const Matrix &x); // 拷贝构造(深拷贝) ~Matrix(); void set(const double *pvalue, int size); // 按行拷贝pvalue指向的数据,要求size=rows*cols,否则抛出异常 void clear(); // 矩阵对象数据项置0 const double& at(int i, int j) const; // 返回矩阵对象索引(i,j)对应的数据项const引用(越界则抛出异常) double& at(int i, int j); // 返回矩阵对象索引(i,j)对应的数据项引用(越界则抛出异常) int rows() const; // 返回矩阵对象行数 int cols() const; // 返回矩阵对象列数 void print() const; // 按行打印数据 private: int n_rows_; // 矩阵对象内元素行数 int n_cols_; // 矩阵对象内元素列数 double *pdata_; // 数据区 };
matrix.cpp
#include "matrix.h" #include <algorithm> #include <cstdlib> #include <iostream> #include <stdexcept> Matrix::Matrix(int n_rows, int n_cols, double value) : n_rows_{n_rows}, n_cols_{n_cols}, pdata_{nullptr} { if (n_rows <= 0 || n_cols <= 0) throw std::invalid_argument("rows and cols must be positive"); pdata_ = new double[n_rows_ * n_cols_]; std::fill_n(pdata_, n_rows_ * n_cols_, value); } Matrix::Matrix(int n_rows, double value): Matrix(n_rows, n_rows, value) { } // 拷贝构造(深拷贝) Matrix::Matrix(const Matrix &x) : n_rows_{x.n_rows_}, n_cols_{x.n_cols_}, pdata_{new double[x.n_rows_ * x.n_cols_]} { std::copy_n(x.pdata_, n_rows_ * n_cols_, pdata_); } // 释放指针指向的内存资源 Matrix::~Matrix() { delete[] pdata_; } void Matrix::set(const double *pvalue, int size) { if(size != n_rows_ * n_cols_) throw std::invalid_argument("size must match"); if (pvalue == nullptr) throw std::invalid_argument("pvalue must not be null"); std::copy_n(pvalue, size, pdata_); } void Matrix::clear() { std::fill_n(pdata_, n_rows_ * n_cols_, 0); } const double& Matrix::at(int i, int j) const { if(i < 0 || i >= n_rows_ || j < 0 || j >= n_cols_) throw std::out_of_range("i must be [0, n_rows_ - 1] and j must be [0, n_cols_ - 1]"); return pdata_[i * n_cols_ + j]; } // 返回矩阵对象索引(i,j)对应的数据项引用(越界则抛出异常) double& Matrix::at(int i, int j) { return const_cast<double&>( static_cast<const Matrix*>(this)->at(i, j) ); } int Matrix::rows() const { return n_rows_; } int Matrix::cols() const { return n_cols_; } // 按行打印数据 void Matrix::print() const { for (int i = 0; i < n_rows_; ++i) { for (int j = 0; j < n_cols_; ++j) { if (j > 0) std::cout << ' '; std::cout << pdata_[i * n_cols_ + j]; } std::cout << '\n'; } }
task4.cpp
#include <cstdlib> #include <iostream> #include <stdexcept> #include "matrix.h" void test1(); void test2(); void output(const Matrix &m, int row_index); int main() { std::cout << "测试1: \n"; test1(); std::cout << "\n测试2: \n"; test2(); return 0; } void test1() { double x[1000] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int n, m; std::cout << "Enter n and m: "; std::cin >> n >> m; Matrix m1(n, m); // 创建矩阵对象m1, 大小n×m m1.set(x, n*m); // 用一维数组x的值按行为矩阵m1赋值 Matrix m2(m, n); // 创建矩阵对象m2, 大小m×n m2.set(x, m*n); // 用一维数组x的值按行为矩阵m1赋值 Matrix m3(n); // 创建一个n×n方阵对象 m3.set(x, n*n); // 用一维数组x的值按行为矩阵m3赋值 std::cout << "矩阵m1: \n"; m1.print(); std::cout << "矩阵m2: \n"; m2.print(); std::cout << "矩阵m3: \n"; m3.print(); } void test2() { Matrix m1(2, 5, -1); const Matrix m2(m1); std::cout << "矩阵m1: \n"; m1.print(); std::cout << "矩阵m2: \n"; m2.print(); m1.clear(); m1.at(0, 0) = 1; m1.at(0, 1) = 2; std::cout << "m1更新后: \n"; std::cout << "矩阵m1第0行 "; output(m1, 0); std::cout << "矩阵m2第0行: "; output(m2, 0); } // 输出矩阵对象row_index行所有元素 void output(const Matrix &m, int row_index) { if(row_index < 0 || row_index >= m.rows()) throw std::out_of_range("row_index must in [0, m.rows()-1]"); std::cout << m.at(row_index, 0); for(int j = 1; j < m.cols(); ++j) std::cout << ", " << m.at(row_index, j); std::cout << '\n'; }
运行结果截图:

问题:set() 是否有风险?如何优化?
有风险:set() 只检查 size 是否等于 rows*cols,无法知道 pvalue 实际指向多长的数组。把 x 改成 double x[5] 后输入 2 3 或 2 5,size 检查仍会通过,但 copy_n 会越界读取,输出垃圾值或崩溃;原来的 x[1000] 因为数组足够大而掩盖了问题。优化应改用 std::vector<double>、std::array 或 std::span 等携带长度的容器,并在复制前检查实际长度;若接口不能改,至少要校验 size、空指针,并由调用者保证缓冲区足够大。
拓展思考:把 pdata_ 换成 std::vector<double>
可以自动深拷贝、自动释放、保证异常安全,仍然保持连续内存,元素访问性能基本不变,代码量更少;这就是 RAII 和“零成本抽象”的体现。
另外,原
const at()的>已改为>=,否则i == n_rows_或j == n_cols_会越界。拷贝赋值运算符本题接口未要求,实际工程中应实现深拷贝或删除,避免浅拷贝导致 double free。
任务5:
源代码:
contact.hpp
#pragma once #include <iostream> #include <string> // 联系人类 class Contact { public: Contact(const std::string &name, const std::string &phone); const std::string &get_name() const; const std::string &get_phone() const; void display() const; private: std::string name_; // 必填项 std::string phone_; // 必填项 }; inline Contact::Contact(const std::string &name, const std::string &phone):name_{name}, phone_{phone} { } inline const std::string& Contact::get_name() const { return name_; } inline const std::string& Contact::get_phone() const { return phone_; } inline void Contact::display() const { std::cout << name_ << ", " << phone_; }contactbook.hpp
#pragma once #include "contact.hpp" #include <algorithm> #include <cstddef> #include <iostream> #include <string> #include <vector> // 通讯录类 class ContactBook { public: void add(const std::string &name, const std::string &phone); // 添加联系人 void remove(const std::string &name); // 移除联系人 void find(const std::string &name) const; // 查找联系人 void display() const; // 显示所有联系人 size_t size() const; private: int index(const std::string &name) const; // 返回联系人在vector内索引,如不存在,返回-1 void sort(); // 按姓名字典序升序排序通讯录 private: std::vector<Contact> contacts_; }; inline void ContactBook::add(const std::string &name, const std::string &phone) { if(index(name) == -1) { contacts_.push_back(Contact(name, phone)); std::cout << name << " add successfully.\n"; sort(); return; } std::cout << name << " already exists. fail to add!\n"; } inline void ContactBook::remove(const std::string &name) { int i = index(name); if(i == -1) { std::cout << name << " not found, fail to remove!\n"; return; } contacts_.erase(contacts_.begin()+i); std::cout << name << " remove successfully.\n"; } inline void ContactBook::find(const std::string &name) const { int i = index(name); if(i == -1) { std::cout << name << " not found!\n"; return; } contacts_[i].display(); std::cout << '\n'; } inline void ContactBook::display() const { for(auto &c: contacts_) { c.display(); std::cout << '\n'; } } inline size_t ContactBook::size() const { return contacts_.size(); } // 返回联系人在contacts内索引; 如不存在,返回-1 inline int ContactBook::index(const std::string &name) const { for (std::size_t i = 0; i < contacts_.size(); ++i) { if (contacts_[i].get_name() == name) return static_cast<int>(i); } return -1; } // 按姓名字典序升序排列通讯录 inline void ContactBook::sort() { std::sort(contacts_.begin(), contacts_.end(), [](const Contact &a, const Contact &b) { return a.get_name() < b.get_name(); }); }task5.cpp
#include "contactbook.hpp" void test() { ContactBook contactbook; std::cout << "1. add contacts\n"; contactbook.add("Bob", "18199357253"); contactbook.add("Alice", "17300886371"); contactbook.add("Linda", "18184538072"); contactbook.add("Alice", "17300886371"); std::cout << "\n2. display contacts\n"; std::cout << "There are " << contactbook.size() << " contacts.\n"; contactbook.display(); std::cout << "\n3. find contacts\n"; contactbook.find("Bob"); contactbook.find("David"); std::cout << "\n4. remove contact\n"; contactbook.remove("Bob"); contactbook.remove("David"); std::cout << "\n5. display contacts\n"; std::cout << "There are " << contactbook.size() << " contacts.\n"; contactbook.display(); } int main() { test(); }运行结果截图:
任务 1:
index()怎么实现?
用 const 线性遍历contacts_,通过get_name() == name区分大小写查找,找到返回下标,否则返回 -1;时间复杂度 O(n)。任务 2:
sort()怎么实现?
用std::sort加 lambda,按get_name()的字典序升序排序;add()成功后调用,保证display()始终有序,平均 O(n log n)。可能追问:
两者设为 private 是因为它们只是内部辅助;姓名查找区分大小写;数据量大时可以改用unordered_map建索引,或改为插入时保持有序。拓展思考:如何扩展成更接近真实手机的通讯录?
保持原接口不变,新增update/search/save/load等函数;增加姓名、电话校验和异常/错误码;用 CSV 或 JSON 持久化;给Contact增加分组字段;模糊检索可转小写后用find;数据量大时用哈希索引,并把校验、存储、显示分层。

浙公网安备 33010602011771号