实验3
实验1
task.cpp
1 #include "window.hpp" 2 #include <iostream> 3 4 void test() { 5 Window w("Demo"); 6 w.add_button("add"); 7 w.add_button("remove"); 8 w.add_button("modify"); 9 w.add_button("add"); 10 w.display(); 11 w.close(); 12 } 13 14 int main() { 15 std::cout << "用组合类模拟简单GUI:\n"; 16 test(); 17 }
window.hpp
1 #pragma once 2 3 #include <iostream> 4 #include <vector> 5 #include <algorithm> 6 #include "button.hpp" 7 8 class Window { 9 public: 10 Window(const std::string& title_); 11 void display() const; 12 void close(); 13 void add_button(const std::string& label); 14 void click_button(const std::string& label); 15 16 private: 17 bool has_button(const std::string& label) const; 18 19 private: 20 std::string title; 21 std::vector<Button> buttons; 22 }; 23 24 Window::Window(const std::string& title_) : title{ title_ } { 25 buttons.emplace_back("close"); 26 } 27 28 inline void Window::display() const { 29 std::string s(40, '*'); 30 std::cout << s << std::endl; 31 std::cout << "window : " << title << std::endl; 32 int cnt = 0; 33 for (const auto& button : buttons) 34 std::cout << ++cnt << ". " << button.get_label() << std::endl; 35 std::cout << s << std::endl; 36 } 37 38 inline void Window::close() { 39 std::cout << "close window '" << title << "'" << std::endl; 40 click_button("close"); 41 } 42 43 inline bool Window::has_button(const std::string& label) const { 44 for (const auto& button : buttons) 45 if (button.get_label() == label) 46 return true; 47 48 return false; 49 } 50 51 inline void Window::add_button(const std::string& label) { 52 if (has_button(label)) 53 std::cout << "button " << label << " already exists!\n"; 54 else 55 buttons.emplace_back(label); 56 } 57 58 inline void Window::click_button(const std::string& label) { 59 for (auto& button : buttons) 60 if (button.get_label() == label) { 61 button.click(); 62 return; 63 } 64 65 std::cout << "no button: " << label << std::endl; 66 }
button.hpp
1 #pragma once 2 #include <iostream> 3 #include<string> 4 class Button { 5 public: 6 Button(const std::string& label_); 7 const std::string& get_label() const; 8 void click(); 9 private: 10 std::string label; 11 }; 12 Button::Button(const std::string& label_) :label{ label_ } { 13 14 } 15 inline const std::string& Button::get_label()const { 16 return label; 17 } 18 inline void Button::click() { 19 std::cout << "Button'" << label << "'clicked\n"; 20 }

问题1:window和button是组合关系,button以动态数组的形式组合在window类中。
问题2:优点,外部可以直接查询窗口是否包含某个按钮,使得查询变得很方便、直观,增加接口灵活性,缺点,把类的内部暴露给了外部,如果有外部调用者基于这个接口做了一些操作,只要这个接口内部发生修改,就可能影响所有基于这个接口的外部代码。
一个类中需要对用户开放的接口应被设为公有,如果一些方法和临时数据仅需要被内部调用,或涉及修改对象状态时,应该设为私有,防止用户误操作导致系统故障或被恶意入侵。
问题3:接口1(返回const std::string&)性能更优,避免了字符串拷贝,但存在潜在的生命周期风险,若原始对象被修改或销毁可能导致悬空引用;接口2(返回const std::string)通过返回值拷贝确保安全性,调用者获得独立对象,但会引入拷贝开销。选择取决于对性能与安全性的权衡:若调用周期可控且追求效率则用接口1,若需长期持有或确保安全则用接口2。
问题4:程序可以正常运行。push_back()在传入通过参数构造的对象时,需要创建一个临时对象,再优先尝试通过移动构造将其加入vector对象,如果元素类型无可用的移动构造函数,则会使用复制构造;而emplace_back()可以直接接收参数,在容器内直接调用构造函数,不需要创建临时对象,性能更高。
实验2
1 #include <iostream> 2 #include <vector> 3 4 void test1(); 5 void test2(); 6 void output1(const std::vector<int>& v); 7 void output2(const std::vector<int>& v); 8 void output3(const std::vector<std::vector<int>>& v); 9 10 int main() 11 { 12 std::cout << "deep copy test1: 标准库vector<int>\n"; 13 test1(); 14 std::cout << "\ndeep copy test2: 标准库vector<int>嵌套使用\n"; 15 test2(); 16 } 17 18 void test1() 19 { 20 std::vector<int> v1(5, 42); 21 const std::vector<int> v2(v1); 22 std::cout << "after copy constructure:"; 23 std::cout << "v1 : "; output1(v1); 24 std::cout << "v2 : "; output1(v2); 25 26 v1.at(0) = -1; 27 28 std::cout << "after modify v1[0]"; 29 std::cout << "v1 = "; output1(v1); 30 std::cout << "v2 = "; output1(v2); 31 } 32 33 void test2() 34 { 35 std::vector<std::vector<int>> v1{ {1,2,3},{4,5,6,7} }; 36 const std::vector<std::vector<int>> v2(v1); 37 std::cout << "after copy constructure:"; 38 std::cout << "v1 : "; output3(v1); 39 std::cout << "v2 : "; output3(v2); 40 41 v1.at(0).push_back(-1); 42 43 std::cout << "after modify v1[0]"; 44 std::cout << "v1 : \n"; output3(v1); 45 std::cout << "v2 : \n"; output3(v2); 46 } 47 48 void output1(const std::vector<int>& v) 49 { 50 if (v.size() == 0) 51 { 52 std::cout << '\n'; 53 return; 54 } 55 56 std::cout << v.at(0); 57 for (auto i = 1; i < v.size(); i++) 58 std::cout << ", " << v.at(i); 59 std::cout << '\n'; 60 } 61 62 void output2(const std::vector<int>& v) 63 { 64 if (v.size() == 0) 65 { 66 std::cout << '\n'; 67 return; 68 } 69 auto it = v.begin(); 70 std::cout << *it; 71 72 for (it = v.begin() + 1; it != v.end(); it++) 73 std::cout << "," << *it; 74 std::cout << '\n'; 75 } 76 77 void output3(const std::vector<std::vector<int>>& v) 78 { 79 if (v.size() == 0) 80 { 81 std::cout << '\n'; 82 return; 83 } 84 for (auto& i : v) 85 output2(i); 86 }

问题1:
1,std::vector<int> v1(5, 42); 是构造函数,创建含 5 个元素,每个元素值为 42 的 vector。
2,const std::vector<int> v2(v1); 是拷贝构造函数,用 v1 初始化 v2。
3,v1、v2 初始时各包含 5 个值为 42 的数据项。
问题2:v1.size() = 2,v2.size() = 2, v1[0].size() = 3
问题3:将 v1.at(0) = -1 写成 v1[0] = -1 能实现相同的修改效果。两者核心区别在于 边界检查:at() 会进行越界检查并在无效访问时抛出异常,而 operator[] 不进行检查,越界访问行为未定义。
问题4:(1)可以输出 -1。因为引用 r 绑定到了 v1 的第一个子 vector,push_back(-1) 后,通过 r 访问其最后一个元素自然就是新添加的 -1。
(2)使用 const& 接收返回值,优势 在于避免了不必要的对象拷贝,节省内存和构造开销;限制 在于无法通过该引用修改所引用的对象。
问题5:
(1)标准库 vector 的复制构造函数实现的是 深复制。证据在于修改 v1 的内容后,v2 保持不变,说明两者数据完全独立。
(2)at() 方法 必须提供 const 重载版本。因为当 v 是普通 vector<int> 时,v.at(0) 返回 int& (可修改);当 v 是 const vector<int> 时,v.at(0) 必须返回 const int& (只读),以满足 const 对象访问的语义正确性。
实验3:
vectorInt.hpp
#pragma once #include <iostream> #include <algorithm> 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_] } { std::fill_n(ptr, n, value); } vectorInt::vectorInt(const vectorInt& vi) : n{ vi.n }, ptr{ new int[n] } { std::copy_n(vi.ptr, vi.n, ptr); } 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) { return const_cast<int&>(static_cast<const vectorInt*>(this)->at(index)); } vectorInt& vectorInt::assign(const vectorInt& vi) { if (this == &vi) return *this; int* ptr_tmp; ptr_tmp = new int[vi.n]; std::copy_n(vi.ptr, vi.n, ptr_tmp); 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; }
task3.cpp
1 #include "vectorInt.hpp" 2 #include <iostream> 3 4 void test1(); 5 void test2(); 6 void output1(const vectorInt& vi); 7 void output2(const vectorInt& vi); 8 9 int main() 10 { 11 std::cout << "测试1: \n"; 12 test1(); 13 14 std::cout << "\n测试2: \n"; 15 test2(); 16 } 17 18 void test1() 19 { 20 int n; 21 std::cout << "Enter n: "; 22 std::cin >> n; 23 24 vectorInt x1(n); 25 for (auto i = 0; i < n; ++i) 26 x1.at(i) = (i + 1) * 10; 27 std::cout << "x1: "; output1(x1); 28 29 vectorInt x2(n, 42); 30 vectorInt x3(x2); 31 x2.at(0) = -1; 32 std::cout << "x2: "; output1(x2); 33 std::cout << "x3: "; output1(x3); 34 } 35 36 void test2() 37 { 38 const vectorInt x(5, 42); 39 vectorInt y; 40 41 y.assign(x); 42 43 std::cout << "x: "; output2(x); 44 std::cout << "y: "; output2(y); 45 } 46 47 void output1(const vectorInt& vi) 48 { 49 if (vi.size() == 0) 50 { 51 std::cout << '\n'; 52 return; 53 } 54 55 std::cout << vi.at(0); 56 for (auto i = 1; i < vi.size(); ++i) 57 std::cout << ", " << vi.at(i); 58 std::cout << '\n'; 59 } 60 61 void output2(const vectorInt& vi) { 62 if (vi.size() == 0) 63 { 64 std::cout << '\n'; 65 return; 66 } 67 68 auto it = vi.begin(); 69 std::cout << *it; 70 71 for (it = vi.begin() + 1; it != vi.end(); ++it) 72 std::cout << ", " << *it; 73 std::cout << '\n'; 74 }

问题1:当尝试用自身给自身赋值时,原代码会在最前做一次判断,可以避免原数据被释放;版本2中直接释放原数据,如果赋值给自身则会导致数据被异常释放,ptr成为野指针。
如果使用new[]分配内存失败报错时,原代码使用临时指针变量来指向分配内存,失败时不会影响到原数据;版本2中将原数有据释放后使用自身的ptr指针来指向分配的内存,如果分配失败,原有数据无法找回,ptr为野指针,安全性较低。
问题2:
(1)作用:将非 const 的 this 指针转换为 const vectorInt*。转换前类型:vectorInt*;转换后:const vectorInt*。目的:调用 const 版本的 at () 接口,复用代码。
(2)作用:移除 const 属性。转换前:const int&;转换后:int&。目的:在非 const 版本中返回可修改的引用,同时复用 const 版本的逻辑。
问题3:编译器会优先选择匹配最完全的重载函数。当const vectorInt类型或通过const指针、引用调用begin()时,选用const版本的begin();当非const类型或通过非const指针、引用调用begin()时,选用非const版本的begin()。
问题4:可以改写。std::fill(ptr,n,value)的功能是将从ptr为起始的n个元素赋值为value;std::copy_n的功能是将从vi.ptr为起始的vi.n个元素复制到以ptr为起始的容器中。
第一处更新是将vectorInt对象中的数据批量赋值,第二处更新是将vi中的数据批量复制到新的对象中,第三处更新是将临时存储的数据批量赋值到原先的对象中。
实验4:
task4.cpp
1 #include <iostream> 2 #include <cstdlib> 3 #include "matrix.hpp" 4 5 void test1(); 6 void test2(); 7 void output(const Matrix& m, int row_index); 8 9 int main() { 10 std::cout << "测试1: \n"; 11 test1(); 12 13 std::cout << "\n测试2: \n"; 14 test2(); 15 } 16 17 void test1() { 18 double x[1000] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 19 20 int n, m; 21 std::cout << "Enter n and m: "; 22 std::cin >> n >> m; 23 24 Matrix m1(n, m); // 创建矩阵对象m1, 大小n×m 25 m1.set(x, n * m); // 用一维数组x的值按行为矩阵m1赋值 26 27 Matrix m2(m, n); // 创建矩阵对象m2, 大小m×n 28 m2.set(x, m * n); // 用一维数组x的值按行为矩阵m1赋值 29 30 Matrix m3(n); // 创建一个n×n方阵对象 31 m3.set(x, n * n); // 用一维数组x的值按行为矩阵m3赋值 32 33 std::cout << "矩阵对象m1: \n"; m1.print(); 34 std::cout << "矩阵对象m2: \n"; m2.print(); 35 std::cout << "矩阵对象m3: \n"; m3.print(); 36 } 37 38 void test2() { 39 Matrix m1(2, 3, -1); 40 const Matrix m2(m1); 41 42 std::cout << "矩阵对象m1: \n"; m1.print(); 43 std::cout << "矩阵对象m2: \n"; m2.print(); 44 45 m1.clear(); 46 m1.at(0, 0) = 1; 47 48 std::cout << "m1更新后: \n"; 49 std::cout << "矩阵对象m1第0行 "; output(m1, 0); 50 std::cout << "矩阵对象m2第0行: "; output(m2, 0); 51 } 52 53 // 输出矩阵对象row_index行所有元素 54 void output(const Matrix& m, int row_index) { 55 if (row_index < 0 || row_index >= m.rows()) { 56 std::cerr << "IndexError: row index out of range\n"; 57 exit(1); 58 } 59 60 std::cout << m.at(row_index, 0); 61 for (int j = 1; j < m.cols(); ++j) 62 std::cout << ", " << m.at(row_index, j); 63 std::cout << '\n'; 64 }
matrix.hpp
1 #pragma once 2 3 #include <iostream> 4 #include <algorithm> 5 #include <cstdlib> 6 7 // 类Matrix声明 8 class Matrix { 9 public: 10 Matrix(int rows_, int cols_, double value = 0); // 构造rows_*cols_矩阵对象, 初值value 11 Matrix(int rows_, double value = 0); // 构造rows_*rows_方阵对象, 初值value 12 Matrix(const Matrix& x); // 深复制 13 ~Matrix(); 14 15 void set(const double* pvalue, int size); // 按行复制pvalue指向的数据,要求size=rows*cols,否则报错退出 16 void clear(); // 矩阵对象数据项置0 17 18 const double& at(int i, int j) const; // 返回矩阵对象索引(i,j)对应的数据项const引用(越界则报错后退出) 19 double& at(int i, int j); // 返回矩阵对象索引(i,j)对应的数据项引用(越界则报错后退出) 20 21 int rows() const; // 返回矩阵对象行数 22 int cols() const; // 返回矩阵对象列数 23 24 void print() const; // 按行打印数据 25 26 private: 27 int n_rows; // 矩阵对象内元素行数 28 int n_cols; // 矩阵对象内元素列数 29 double* ptr; // 数据区 30 }; 31 32 Matrix::Matrix(int rows_, int cols_, double value) : n_rows{ rows_ }, n_cols{ cols_ }, ptr{ new double[rows_ * cols_] } 33 { 34 std::fill_n(ptr, n_rows * n_cols, value); 35 } 36 Matrix::Matrix(int rows_, double value) : n_rows{ rows_ }, n_cols{ rows_ }, ptr{ new double[rows_ * rows_] } 37 { 38 std::fill_n(ptr, n_rows * n_rows, value); 39 } 40 Matrix::Matrix(const Matrix& x) : n_rows{ x.n_rows }, n_cols{ x.n_cols }, ptr{ new double[x.n_rows * x.n_cols] } 41 { 42 std::copy_n(x.ptr, x.n_rows * x.n_cols, ptr); 43 } 44 Matrix::~Matrix() 45 { 46 delete[] ptr; 47 } 48 49 void Matrix::set(const double* pvalue, int size) 50 { 51 if (n_rows * n_cols != size) 52 { 53 std::cerr << "Set Size Not Fit Matrix Size"; 54 return; 55 } 56 57 for (int i = 0; i < size; i++) 58 ptr[i] = pvalue[i]; 59 } 60 61 void Matrix::clear() 62 { 63 for (int i = 0; i < (n_rows * n_cols); i++) 64 ptr[i] = 0; 65 } 66 67 const double& Matrix::at(int i, int j) const 68 { 69 if (i < 0 || j < 0 || i >= n_rows || j >= n_cols) 70 { 71 std::cerr << "Const At Not Fit Matrix Size"; 72 ; 73 } 74 return ptr[i * n_cols + j]; 75 } 76 77 double& Matrix::at(int i, int j) 78 { 79 return const_cast<double&>(static_cast<const Matrix*>(this)->at(i, j)); 80 } 81 82 int Matrix::rows() const 83 { 84 return n_rows; 85 } 86 87 int Matrix::cols() const 88 { 89 return n_cols; 90 } 91 92 void Matrix::print() const 93 { 94 if (n_rows == 0 || n_cols == 0) 95 { 96 std::cout << '\n'; 97 return; 98 } 99 for (int i = 0; i < n_rows; i++) 100 { 101 int j = 0; 102 std::cout << ptr[i * n_cols]; 103 for (j = 1; j < n_cols; j++) 104 { 105 std::cout << ", " << ptr[i * n_cols + j]; 106 } 107 std::cout << '\n'; 108 } 109 }

实验5:
1 #pragma once 2 3 #include <iostream> 4 #include <string> 5 6 // 联系人类 7 class Contact { 8 public: 9 Contact(const std::string& name_, const std::string& phone_); 10 11 const std::string& get_name() const; 12 const std::string& get_phone() const; 13 void display() const; 14 15 private: 16 std::string name; // 必填项 17 std::string phone; // 必填项 18 }; 19 20 Contact::Contact(const std::string& name_, const std::string& phone_) :name{ name_ }, phone{ phone_ } { 21 } 22 23 const std::string& Contact::get_name() const { 24 return name; 25 } 26 27 const std::string& Contact::get_phone() const { 28 return phone; 29 } 30 31 void Contact::display() const { 32 std::cout << name << ", " << phone; 33 }
1 # pragma once 2 3 #include <iostream> 4 #include <string> 5 #include <vector> 6 #include <algorithm> 7 #include "contact.hpp" 8 9 // 通讯录类 10 class ContactBook { 11 public: 12 void add(const std::string& name, const std::string& phone); // 添加联系人 13 void remove(const std::string& name); // 移除联系人 14 void find(const std::string& name) const; // 查找联系人 15 void display() const; // 显示所有联系人 16 size_t size() const; 17 18 private: 19 int index(const std::string& name) const; // 返回联系人在contacts内索引,如不存在,返回-1 20 void sort(); // 按姓名字典序升序排序通讯录 21 22 private: 23 std::vector<Contact> contacts; 24 }; 25 26 void ContactBook::add(const std::string& name, const std::string& phone) { 27 if (index(name) == -1) { 28 contacts.push_back(Contact(name, phone)); 29 std::cout << name << " add successfully.\n"; 30 sort(); 31 return; 32 } 33 34 std::cout << name << " already exists. fail to add!\n"; 35 } 36 37 void ContactBook::remove(const std::string& name) { 38 int i = index(name); 39 40 if (i == -1) { 41 std::cout << name << " not found, fail to remove!\n"; 42 return; 43 } 44 45 contacts.erase(contacts.begin() + i); 46 std::cout << name << " remove successfully.\n"; 47 } 48 49 void ContactBook::find(const std::string& name) const { 50 int i = index(name); 51 52 if (i == -1) { 53 std::cout << name << " not found!\n"; 54 return; 55 } 56 57 contacts[i].display(); 58 std::cout << '\n'; 59 } 60 61 void ContactBook::display() const { 62 for (auto& c : contacts) { 63 c.display(); 64 std::cout << '\n'; 65 } 66 } 67 68 size_t ContactBook::size() const { 69 return contacts.size(); 70 } 71 72 // 已补足1:int index(const std::string &name) const;实现 73 // 返回联系人在contacts内索引; 如不存在,返回-1 74 int ContactBook::index(const std::string& name) const 75 { 76 for (size_t i = 0; i < contacts.size(); i++) 77 { 78 if (contacts.at(i).get_name() == name) 79 return i; 80 } 81 return -1; 82 } 83 84 85 // 已补足2:void ContactBook::sort();实现 86 // 按姓名字典序升序排序通讯录 87 void ContactBook::sort() 88 { 89 int n = contacts.size(); 90 for (size_t i = 0; i < n - 1; i++) 91 { 92 for (int j = 0; j < n - i - 1; j++) 93 { 94 if (contacts.at(j).get_name() > contacts.at(j + 1).get_name()) 95 std::swap(contacts.at(j), contacts.at(j + 1)); 96 } 97 } 98 }
task5.cpp
1 #include "contactBook.hpp" 2 3 void test() { 4 ContactBook contactbook; 5 6 std::cout << "1. add contacts\n"; 7 contactbook.add("Bob", "18199357253"); 8 contactbook.add("Alice", "17300886371"); 9 contactbook.add("Linda", "18184538072"); 10 contactbook.add("Alice", "17300886371"); 11 12 std::cout << "\n2. display contacts\n"; 13 std::cout << "There are " << contactbook.size() << " contacts.\n"; 14 contactbook.display(); 15 16 std::cout << "\n3. find contacts\n"; 17 contactbook.find("Bob"); 18 contactbook.find("David"); 19 20 std::cout << "\n4. remove contact\n"; 21 contactbook.remove("Bob"); 22 contactbook.remove("David"); 23 } 24 25 int main() { 26 test(); 27 }


浙公网安备 33010602011771号