实验作业3
实验三:类和对象基础编程2
实验任务1
代码
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(); }
window.hpp
#pragma once #include <iostream> #include <vector> #include <algorithm> #include "button.hpp" // 窗口类 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; private: std::string title; std::vector<Button> buttons; }; 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; }
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; }; 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"; }
运行截图

问题
问题1
是组合关系。因为Window 类中包含 std::vector<Button> buttons 成员,Button 对象作为 Window 的一部分存在,两者生命周期一致,当 Window 对象销毁时,其内部的 Button 对象也会被销毁;Button 对象由 Window 直接管理,外部无法直接访问或操作这些 Button。
问题2
(1)优点:允许外部查询按钮是否存在,增加灵活性。
缺点:1.用户可能重复实现 click_button 等功能,比如先 has_button 再 click_button。
2.暴露实现细节,用户需知道按钮用 vector 存储,且通过 label 匹配。
3.破坏封装性,用户可能依赖此函数实现逻辑,导致高耦合,如果未来数据结构改了的话,会导致用户的代码也得跟着一起改。
(2)1.用户是否需要的角度:如果该函数是类提供给外部的功能,是用户必需的,则设为public;如果仅用于内部辅助,用户没必要用到,则设为private。
2.是否仅为内部实现细节的角度:如果该函数是内部实现的一部分,并不希望用户调用,则设为private,避免用户依赖内部细节,否则要看情况,酌情考虑public。
3.是否易破坏对象状态的角度:如果该函数可能破坏对象的状态,修改内部数据,或者执行某些不该由用户直接触发的操作,则应该设为private,并通过public函数封装。
问题3
(1)性能: 接口1:返回常引用,避免了字符串的拷贝,性能更高,特别是当字符串较长时。
接口2:返回字符串的副本(值),会进行拷贝,性能相对较低。
(2)安全性: 接口1:返回引用,虽然避免了拷贝,但需要注意返回的引用的生命周期。这里返回的是成员变量的引用,而成员变量的生命周期与对象一致,只要调用者不在对象销毁后使用该引用,则是安全的。但返回引用会暴露内部数据,虽然加了const,但外部仍然可以通过这个引用持有数据,而且如果外部保存了这个引用,而内部数据改变,按钮的标签被修改或者对象被销毁,则引用可能失效或悬空。
接口2:返回副本,外部得到的是全新的字符串,与内部数据无关,因此更安全,不会因为内部数据的改变而受影响,也不会出现悬空引用。
问题4
程序运行正常
使用push_back(Button(label)),会构造临时 Button 对象,而 emplace_back(label)直接在容器内构造 Button,无临时对象。前者有额外开销,后者更高效,甚至后者更简洁。
实验任务2
代码
#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(); } 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.at(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: "; output3(v1); std::cout << "v2: "; output3(v2); v1.at(0).push_back(-1); std::cout << "**********修改v1[0]后**********\n"; std::cout << "v1: \n"; output3(v1); std::cout << "v2: \n"; output3(v2); } // 使用xx.at()+循环输出vector<int>数据项 void output1(const std::vector<int> &v) { if(v.size() == 0) { std::cout << '\n'; return; } std::cout << v.at(0); for(auto i = 1; i < v.size(); ++i) std::cout << ", " << v.at(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
构造1:调用 v1 的构造函数,创建包含 5个值为42 的整数向量。
构造2:调用 v2 的拷贝构造函数,深复制 v1 的所有元素。
v1,v2各包含5个值为42的元素。
问题2
因为外层容器有2个子向量,所以v1.size() = v2.size() = 2
因为第一个子向量有3个元素,所以v1[0].size() = 3
问题3
能实现同样的效果。
区别:at():进行边界检查,越界时抛出 std::out_of_range 异常。
operator[]:不检查边界,越界行为未定义,可能崩溃或数据损坏。
问题4
(1)可以,r 直接引用 v1[0] 的内存,push_back(-1) 后 r.size()-1 位置上就是 -1。
(2)优点:避免拷贝开销,且防止意外修改。
限制:不能通过 cr 调用非 const 成员函数。
问题5
(1)是深复制,因为修改 v1 后 v2 不受影响,说明每个元素是独立复制的。
(2)v.at(0) 返回可修改元素的引用T&,题中就是int型元素的引用;
const_v.at(0) 返回只读引用 const T&,题中就是const int型元素的引用。
at()必须提供 const 重载版本,否则 const 对象无法调用。
实验任务3
代码
task3.cpp
#include "vectorInt.hpp" #include <iostream> void test1(); void test2(); void output1(const vectorInt &vi); void output2(const vectorInt &vi); int main() { std::cout << "测试1: \n"; test1(); std::cout << "\n测试2: \n"; test2(); } 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); } // 使用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'; }
vectorInt.hpp
#pragma once #include <iostream> // 动态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 *ptr; // 数据区 }; vectorInt::vectorInt():n{0}, ptr{nullptr} { } vectorInt::vectorInt(int n_): n{n_}, ptr{new int[n]} { } vectorInt::vectorInt(int n_, int value): n{n_}, ptr{new int[n_]} { for(auto i = 0; i < n; ++i) ptr[i] = value; } vectorInt::vectorInt(const vectorInt &vi): n{vi.n}, ptr{new int[n]} { for(auto i = 0; i < n; ++i) ptr[i] = vi.ptr[i]; } vectorInt::~vectorInt() { delete [] ptr; } int vectorInt::size() const { return n; } const int& vectorInt::at(int index) const { if(index < 0 || index >= n) { std::cerr << "IndexError: index out of range\n"; std::exit(1); } return ptr[index]; } int& vectorInt::at(int index) { if(index < 0 || index >= n) { std::cerr << "IndexError: index out of range\n"; std::exit(1); } return ptr[index]; } vectorInt& vectorInt::assign(const vectorInt &vi) { if(this == &vi) return *this; int *ptr_tmp; ptr_tmp = new int[vi.n]; for(int i = 0; i < vi.n; ++i) ptr_tmp[i] = vi.ptr[i]; delete[] ptr; n = vi.n; ptr = ptr_tmp; return *this; } int* vectorInt::begin() { return ptr; } int* vectorInt::end() { return ptr+n; } const int* vectorInt::begin() const { return ptr; } const int* vectorInt::end() const { return ptr+n; }
运行截图

问题
问题1
相比原来的代码,delete[] ptr;前置,则当 this == &vi 时,delete[] ptr 会直接销毁自身数据区,后续 vi.ptr[i] 访问的是已被释放的内存;若 new int[n] 内存分配失败,则ptr 已释放但 n 未更新,后续操作将访问无效内存,产生垂悬指针。
原实现通过通过临时缓冲区和自赋值检查,确保自赋值的安全,而且先分配新内存,成功后再释放旧内存,资源也不可能泄漏。
问题2
static_cast<const vectorInt*>(this)作用:将 this 指针转为指向 const 类型的指针。目的:匹配 const 版本的 at() 或其他const 成员函数的调用。
(2) const_cast<int&>(...)作用:移除 const 属性。目的:适配非 const 接口的返回值类型。
问题3
(1)v2为const 对象,优先匹配 const 修饰的重载版本;v1为非 const 对象,优先匹配非 const 版本。
适用场景:int* begin() 需通过迭代器修改元素;const int* begin() const 适用于只读访问。
(2)迭代器本质的理解
让指针变得更安全(?
问题4
可以。功能:std::fill_n(ptr, n, value) 填充 n 个 value 到 ptr 地址,相当于 for(i=0;i<n;) ptr[i]=value;;std::copy_n(src, n, dest) :从 src 复制 n 元素到 dest,相当于 for(i=0;i<n;) dest[i]=src[i];。
实验任务4
代码
task4.cpp
#include <iostream> #include <cstdlib> #include "matrix.hpp" 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(); } 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, 3, -1); const Matrix m2(m1); std::cout << "矩阵对象m1: \n"; m1.print(); std::cout << "矩阵对象m2: \n"; m2.print(); m1.clear(); m1.at(0, 0) = 1; 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()) { std::cerr << "IndexError: row index out of range\n"; exit(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'; }
matrix.hpp
#pragma once #include <iostream> #include <algorithm> #include <cstdlib> // 类Matrix声明 class Matrix { public: Matrix(int rows_, int cols_, double value = 0); // 构造rows_*cols_矩阵对象, 初值value Matrix(int rows_, double value = 0); // 构造rows_*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 *ptr; // 数据区 }; // 构造rows_*cols_矩阵对象, 初值value Matrix::Matrix(int rows_, int cols_, double value) : n_rows(rows_), n_cols(cols_), ptr(nullptr) { if (n_rows <= 0 || n_cols <= 0) { std::cerr << "ValueError: invalid matrix size\n"; std::exit(1); } // 分配连续内存 ptr = new double[n_rows * n_cols]; // 初始化为value for (int i = 0; i < n_rows * n_cols; ++i) ptr[i] = value; } // 构造rows_*rows_方阵对象, 初值value Matrix::Matrix(int rows_, double value) : Matrix(rows_, rows_, value) { } // 深复制 Matrix::Matrix(const Matrix &x) : n_rows(x.n_rows), n_cols(x.n_cols), ptr(nullptr) { if (n_rows <= 0 || n_cols <= 0) { ptr = nullptr; return; } ptr = new double[n_rows * n_cols]; std::copy(x.ptr, x.ptr + (n_rows * n_cols), ptr); } // 析构 Matrix::~Matrix() { delete [] ptr; ptr = nullptr; } // 按行复制pvalue指向的数据,要求size=rows*cols,否则报错退出 void Matrix::set(const double *pvalue, int size) { if (!pvalue) { std::cerr << "ValueError: null pointer in set\n"; std::exit(1); } if (size != n_rows * n_cols) { std::cerr << "ValueError: size mismatch in set\n"; std::exit(1); } std::copy(pvalue, pvalue + size, ptr); } // 矩阵对象数据项置0 void Matrix::clear() { if (ptr) { std::fill(ptr, ptr + (n_rows * n_cols), 0.0); } } // 返回矩阵对象索引(i,j)对应的数据项const引用(越界则报错后退出) const double& Matrix::at(int i, int j) const { if (i < 0 || i >= n_rows || j < 0 || j >= n_cols) { std::cerr << "IndexError: index out of range\n"; std::exit(1); } return ptr[i * n_cols + j]; } // 非const 版本 double& Matrix::at(int i, int j) { if (i < 0 || i >= n_rows || j < 0 || j >= n_cols) { std::cerr << "IndexError: index out of range\n"; std::exit(1); } return ptr[i * n_cols + 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) { if (n_cols > 0) { std::cout << at(i, 0); for (int j = 1; j < n_cols; ++j) std::cout << ", " << at(i, j); } std::cout << '\n'; } }
运行截图

拓展思考
std::vector 自动管理内存,不需要手写析构、复制构造和拷贝赋值,避免内存泄漏与悬挂指针;在异常发生时也能保证已分配资源被释放。td::vector 保证元素在连续内存上存放,对大多数场景性能无损;对需要极限优化的场景可以通过 data() 获取原始指针。构造/复制/移动/析构等由标准容器处理,代码量明显减少,逻辑更清晰,减少因手写资源管理而引入的 bug,后续添加功能也更容易实现。所以说抽象带来更高层次的安全与可读性,而在常规用例下并不会带来运行时开销。
实验任务5
代码
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"); } int main() { test(); }
contackBook.hpp
# pragma once #include <iostream> #include <string> #include <vector> #include <algorithm> #include "contact.hpp" // 通讯录类 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; // 返回联系人在contacts内索引,如不存在,返回-1 void sort(); // 按姓名字典序升序排序通讯录 private: std::vector<Contact> contacts; }; 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"; } 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"; } 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'; } void ContactBook::display() const { for(auto &c: contacts) { c.display(); std::cout << '\n'; } } size_t ContactBook::size() const { return contacts.size(); } // 待补足1:int index(const std::string &name) const;实现 // 返回联系人在contacts内索引; 如不存在,返回-1 int ContactBook::index(const std::string &name) const { for (size_t i = 0; i < contacts.size(); ++i) { if (contacts[i].get_name() == name) { return static_cast<int>(i); } } return -1; } // 待补足2:void ContactBook::sort();实现 // 按姓名字典序升序排序通讯录 void ContactBook::sort() { std::sort(contacts.begin(), contacts.end(), [](const Contact &a, const Contact &b) { return a.get_name() < b.get_name(); }); }
contack.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; // 必填项 }; Contact::Contact(const std::string &name_, const std::string &phone_):name{name_}, phone{phone_} { } const std::string& Contact::get_name() const { return name; } const std::string& Contact::get_phone() const { return phone; } void Contact::display() const { std::cout << name << ", " << phone; }
运行截图
思考
添加“修改联系人”接口(按姓名或 ID 修改姓名/号码/其他字段);保留现有 add/remove/find/display 接口以兼容已有调用。
内部使用不可变 ID 来定位联系人;在添加/修改时验证手机号格式、姓名非空;对于非法输入返回明确错误。
将内存中的通讯录与持久化存储同步(如本地 JSON/CSV、SQLite、或通过平台 API);设计保存/加载接口,最好支持定期自动保存与显式保存。
支持联系人归属多个组或标签;支持多个电话号码、电子邮件、地址、备注等,使用键-值或结构体表示可扩展属性,不仅方便还友好。
实现按姓名/拼音/号码的模糊匹配与快速检索(数据结构乱入)。
为了保险起见,还需自动实现重复联系人检测与合并,最好再整点交互式提示。
说白了就把 Contact 扩展为不可变 ID + 可变字段的结构,便于引用和版本控制。
分离数据存储层、业务逻辑层、显示层;
为关键操作添加日志。

浙公网安备 33010602011771号