实验三
#任务1
##代码
#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(); }
#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; }
#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:是组合关系
问题2:
(1)优点:允许类的外部使用者直接判断窗口中是否存在某个标签的按钮,增加了接口的灵活性。
风险:破坏了类的 “封装性”。若后续修改Window内部存储按钮的方式,has_button的实现逻辑可能需同步修改,此时所有依赖该公有接口的外部代码都会受到影响,增加了代码维护成本和耦合度
(2)是否属于内部实现细节:若函数逻辑与类的内部数据结构强绑定,修改内部结构可能导致函数逻辑变化,则属于实现细节,应设为private
是否可能破坏对象状态:若函数存在直接修改内部私有成员或绕过安全校验的风险,需设为privaye
问题3:接口1仅返回对象内部label成员的引用,无需创建新的string对象,无内存拷贝开销,性能高效,接口2会创建label成员的临时副本,将副本返回给调用者,存在string对象的拷贝构造和析构开销
接口1通过const修饰限制了外部修改,接口2返回的是临时副本,外部修改副本不会影响,都安全
问题4:可正常运行
#任务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:
对于std::vector<int> v1(5, 42);:该行调用vector的带参构造函数,功能是创建一个包含 5 个元素的vector对象,且每个元素的初始值均为 42,因此 v1 包含 5 个值为 42 的数据项
对于const std::vector<int> v2(v1);:该行调用vector的复制构造函数,功能是创建一个新的vector对象 v2,其元素完全复制 v1 的元素,因此 v2 同样包含 5 个值为 42 的数据项
问题2:v1.size() = 2 v2.size() = 2 v1[0].size() = 3
问题3:能实现同等效果
核心区别:
越界检查:at()会进行严格的索引越界检查,若索引小于 0 或大于等于vector的元素个数,会抛出out_of_range异常;而[]不进行越界检查,若索引越界,会访问非法内存,导致程序崩溃
使用场景:追求安全性(如用户输入的不确定索引)时用at();追求极致性能(如确定索引合法的循环遍历)时用[]
问题4:(1)能输出 - 1。v1.at(0)返回 v1 中第一个一维vector的引用,将该引用赋值给 r 后,r 与v1.at(0)指向同一个一维vector;执行push_back(-1)后,该一维vector的最后一个元素就是 - 1,而r.size() - 1正好是最后一个元素的索引,通过r.at(r.size() - 1)可访问到该元素
(2)优势:无需创建v1.at(0)对应一维vector的副本,仅占用引用变量的少量内存。限制:const修饰限制了 r 的权限,通过 r 无法修改其指向的一维vector
问题5:(1)深复制
(2)当 v 是vector<int>(非const)时,v.at(0)返回int&,当 v 是const vector<int>(const)时,v.at(0)返回const int&,推断:at()必须提供带const修饰的重载版本
#任务3
##代码
#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; }
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'; }
##运行测试截图

##问题回答
问题1:
自赋值导致的内存泄漏与崩溃:若vi与当前对象自赋值,版本 2 会先执行delete[] ptr释放当前对象的内存,随后执行ptr = new int[n]时,n = vi.n,最终导致内存分配异常或程序崩溃
问题2:
(1)static_cast<const vectorInt*>(this)
作用:将非const的this指针强制转换为const的this指针
转换前后类型:转换前this的类型是vectorInt*;转换后this的类型是const vectorInt*
转换目的:强制调用const版本的at()成员函数
(2) const_cast<int&>()
作用:移除const属性的强制类型转换
转换前后类型:转换前,const版本at()的返回类型是const int&;转换后,返回类型是int&
转换目的:匹配非const版本at()的返回值要求
问题3:编译器选择逻辑:根据调用者(this指针)的const属性匹配
重载版本使用场景总结:
非const版本begin()/end():适配非const的vectorInt对象,返回非const指针(int*),允许通过指针修改对象内部的元素值(如*it1 = 10)
const版本begin()/end():适配const的vectorInt对象,返回const指针(const int*),仅允许通过指针读取元素值,禁止修改(符合const对象 “只读不写” 的特性)
问题4:可以,
std::fill_n(ptr, n, value):连续对n个int类型的元素赋值为value
std::copy_n(vi.ptr, vi.n, ptr):从源指针vi.ptr指向的内存地址开始,连续复制vi.n个int类型的元素,到目标指针ptr指向的内存地址
std::copy_n(vi.ptr, vi.n, ptr_tmp):从源指针vi.ptr指向的内存地址开始,连续复制vi.n个int类型的元素,到临时指针ptr_tmp指向的内存地址
#任务4
##代码
#pragma once // 类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); // 按行复制数据,size需等于rows*cols void clear(); // 矩阵元素全部置0 const double& at(int i, int j) const; // const版本元素访问(越界报错) double& at(int i, int j); // 非const版本元素访问(越界报错) int rows() const; // 返回行数 int cols() const; // 返回列数 void print() const; // 按行打印矩阵 private: int n_rows; // 行数 int n_cols; // 列数 double *ptr; // 连续内存数据区,存储矩阵元素(按行优先存储) };
#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(); return 0; } // 测试1:普通矩阵、方阵构造与set()赋值 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); // 构造n×m普通矩阵 m1.set(x, n * m); // 按行赋值(x的前n×m个元素) Matrix m2(m, n); // 构造m×n普通矩阵 m2.set(x, m * n); // 按行赋值 Matrix m3(n); // 构造n×n方阵 m3.set(x, n * n); // 按行赋值 std::cout << "矩阵对象m1: \n"; m1.print(); std::cout << "矩阵对象m2: \n"; m2.print(); std::cout << "矩阵对象m3: \n"; m3.print(); } // 测试2:深复制验证(拷贝构造后修改原对象,副本不受影响) void test2() { Matrix m1(2, 3, -1); // 构造2×3矩阵,所有元素初值-1 const Matrix m2(m1); // 拷贝构造m2(深复制) std::cout << "矩阵对象m1: \n"; m1.print(); std::cout << "矩阵对象m2: \n"; m2.print(); m1.clear(); // m1清空(元素置0) m1.at(0, 0) = 1; // 修改m1(0,0)为1 std::cout << "m1更新后: \n"; std::cout << "矩阵对象m1第0行: "; output(m1, 0); std::cout << "矩阵对象m2第0行: "; output(m2, 0); // m2应仍为-1,验证深复制 } // 辅助函数:输出矩阵指定行的所有元素(越界会报错) 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"; std::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"; }
#include "matrix.hpp" #include <iostream> #include <cstdlib> using namespace std; Matrix::Matrix(int rows_, int cols_, double value) : n_rows(rows_), n_cols(cols_) { if (rows_ <= 0 || cols_ <= 0) { cout << "行数/列数不能为负数!\n" << endl; ptr = nullptr; return ; } ptr = new double[rows_ * cols_]; for (int i = 0; i < rows_ * cols_; ++i) { ptr[i] = 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 = new double[n_rows * n_cols]; for (int i = 0; i < n_rows * n_cols; ++i) { ptr[i] = x.ptr[i]; } } Matrix::~Matrix() { delete[] ptr; } void Matrix::set(const double *pvalue, int size) { if (size != n_rows * n_cols) { cerr << "Error: Data size does not match matrix size!"<<endl; exit(1); } for (int i = 0; i < size; ++i) { ptr[i] = pvalue[i]; } } void Matrix::clear() { fill(ptr,ptr + n_rows*n_cols,0.0); } const double& Matrix::at(int i, int j) const { if (i < 0 || i >= n_rows || j < 0 || j >= n_cols) { cerr << "Error: Index (" << i << "," << j << ") out of range!\n"; exit(1); } return ptr[i * n_cols + j]; } double& Matrix::at(int i, int j) { if(i<0||j<0||i>=n_rows||j>=n_cols){ cerr<<"indexWrong"; 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) { for (int j = 0; j < n_cols; ++j) { if (j > 0) { cout << ", "; } cout << at(i, j); } cout << endl; } }
##运行测试截图

#任务5
##代码
#pragma once #include <string> #include <vector> // 联系人类:存储单个联系人信息 class Contact { public: Contact(const std::string& name, const std::string& phone, const std::string& email); std::string getName() const; std::string getPhone() const; std::string getEmail() const; void setPhone(const std::string& phone); void setEmail(const std::string& email); private: std::string name; // 姓名(唯一标识) std::string phone; // 电话 std::string email; // 邮箱 }; // 通讯录类:管理联系人集合(组合关系:AddressBook has-a Contact) class AddressBook { public: void addContact(const Contact& contact); // 添加联系人(去重) bool deleteContact(const std::string& name); // 删除联系人(按姓名) Contact* findContact(const std::string& name); // 查找联系人(按姓名) void showAllContacts() const; // 显示所有联系人(排序后) private: std::vector<Contact> contacts; // 存储联系人的容器 int findIndexByName(const std::string& name) const; // 私有工具:查找姓名对应的索引 };
#include <iostream> #include <string> #include "contact.hpp" using namespace std; // 显示菜单 void showMenu() { cout << "\n===== 简易通讯录系统 =====\n"; cout << "1. 添加联系人\n"; cout << "2. 删除联系人\n"; cout << "3. 查找联系人\n"; cout << "4. 显示所有联系人\n"; cout << "0. 退出系统\n"; cout << "==========================\n"; cout << "请输入操作编号:"; } int main() { AddressBook addrBook; int choice; string name, phone, email; while (true) { showMenu(); cin >> choice; cin.ignore(); // 忽略输入编号后的换行符 switch (choice) { case 1: // 添加联系人 cout << "\n请输入联系人姓名:"; getline(cin, name); cout << "请输入联系人电话:"; getline(cin, phone); cout << "请输入联系人邮箱:"; getline(cin, email); addrBook.addContact(Contact(name, phone, email)); break; case 2: // 删除联系人 cout << "\n请输入要删除的联系人姓名:"; getline(cin, name); addrBook.deleteContact(name); break; case 3: // 查找联系人 cout << "\n请输入要查找的联系人姓名:"; getline(cin, name); Contact* found = addrBook.findContact(name); if (found) { cout << "\n找到联系人:\n"; cout << "姓名:" << found->getName() << "\n"; cout << "电话:" << found->getPhone() << "\n"; cout << "邮箱:" << found->getEmail() << "\n"; } break; case 4: // 显示所有联系人 addrBook.showAllContacts(); break; case 0: // 退出系统 cout << "\n感谢使用,再见!\n"; return 0; default: cout << "\n输入错误!请输入0-4之间的编号!\n"; break; } } }
#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; // 返回联系人索引,不存在返回-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(); } // 补全:查找联系人索引 int ContactBook::index(const std::string &name) const { for (int i = 0; i < contacts.size(); i++) { if (contacts[i].get_name() == name) { return i; // 找到返回索引 } } return -1; // 未找到返回-1 } // 补全:按姓名字典序升序排序 void ContactBook::sort() { std::sort(contacts.begin(), contacts.end(), [](const Contact &a, const Contact &b) { return a.get_name() < b.get_name(); // 按姓名升序 }); }
##运行测试截图


浙公网安备 33010602011771号