实验三
实验任务一:
#include <iostream> #include <string> class Button { public: Button(const std::string &label_); const std::string& get_label() const; //‘&’不是函数的引用,而是一个“返回值为const std::string&的成员函数” 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"; } button.hpp
#include <iostream> #include <string> class Button { public: Button(const std::string &label_); const std::string& get_label() const; //‘&’不是函数的引用,而是一个“返回值为const std::string&的成员函数” 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"; } button.hpp
#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(); } task1.cpp
运行结果为:

问题一:
是的
问题二:
(1)将 `has_button` 从私有改为公有接口的主要优点是增强了类的灵活性,允许外部代码在操作前检查按钮存在性,便于实现条件逻辑和测试验证。然而,这会破坏封装性原则,暴露内部状态细节,可能导致外部代码绕过设计意图直接依赖实现细节,增加维护负担,并在多线程环境下引入竞态条件风险。总体而言,这种改动在需要外部查询功能时提供便利,但需要权衡对软件设计质量和长期维护性的影响。
(2)设计类成员函数的公私性时,应遵循"最小暴露原则":仅将类对外承诺的核心功能设为public,使用户能完成预期任务而不破坏对象状态;将内部实现细节、辅助方法或可能破坏对象一致性的操作设为private,防止用户依赖易变的实现细节。关键在于站在使用者角度思考——隐藏该函数是否影响类的正常使用?若不影响则应为private,以维护封装性和未来修改的灵活性。
问题三:
接口1性能更优但需注意对象生命周期,接口2安全性更高但性能有代价,应根据具体使用场景权衡选择。在Button生命周期可控且需要高效访问的场景下,接口1是更佳选择。
问题四:
`emplace_back` 与 `push_back` 的核心差别在于构造方式:`push_back` 需要先构造临时对象再拷贝/移动到容器,而 `emplace_back` 直接在容器内存中构造对象,避免了临时对象的创建和拷贝开销。在将 `push_back(Button(xxx))` 改为 `emplace_back(xxx)` 后程序正常运行,且性能更优,因为省去了临时 Button 对象的构造和拷贝步骤,特别对于自定义类对象这种改进能提升效率。
实验任务二:
#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); } task2.cpp
运行结果为:

问题一:
这行代码 `std::vector<int> v1(5,42);` 使用 vector 的填充构造函数创建了 v1,它包含 5 个元素,每个元素的值都是 42;随后通过拷贝构造函数 `const std::vector<int> v2(v1)` 创建 v2,它复制了 v1 的所有内容,因此 v2 同样包含 5 个值为 42 的元素。两者在构造完成后具有完全相同的数据。
问题二:
v1 和 v2 都是二维 vector,各包含 2 行,其中第一行有 3 个元素,第二行有 4 个元素。
问题三:
在当前代码中,由于索引 0 肯定在有效范围内,两种写法效果相同,但 at() 提供了更好的安全性保障。
问题四:
(1)通过 v1.at(0).push_back(-1) 已向v1的第一个子vector末尾添加了元素-1,而 v1.at(0) 返回的是该子vector的引用,因此用 std::vector<int> &r 接收后,r成为这个子vector的别名,r.at(r.size()-1) 自然能访问到最后一个元素-1,所以能够正确输出。
(2)使用const &接收返回值的主要优势是避免对象拷贝,节省内存和提高性能,同时提供只读安全保证防止意外修改;限制在于无法通过该引用修改对象内容,只能调用const成员函数,在需要修改操作的场景下会受到约束。这种用法在只需读取而不需修改数据时是最佳选择。
问题五:
(1)从程序运行结果可见,修改v1后v2保持不变,且向v1[0]添加元素不影响v2,这证明vector的复制构造函数实现的是深复制,会递归复制所有元素及其嵌套内容,创建完全独立的内存空间,而非共享数据的浅复制。
(2)at()必须提供const重载版本,因为当v是普通vector时at(0)返回int&允许修改,而当v是const vector时需返回const int&保证只读访问,这既符合const正确性要求,又能防止通过接口意外修改const对象内容,是C++语言规范的基本要求。
实验任务三:
#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; } vectorInt.hpp
#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'; } task3.cpp
运行结果为:

问题一:
版本2的assign实现存在严重安全隐患:它未处理自赋值情况,当对象自我赋值时会立即删除自身数据导致后续访问已释放内存;同时缺乏异常安全保证,如果在new分配内存时失败,对象将处于资源泄漏的无效状态;此外直接删除原有资源而没有备份机制,违背了RAII原则和强异常安全要求,可能引发程序崩溃或数据损坏。
问题二:
(1)static_cast<const vectorInt*>(this) 的作用是将非 const 的 vectorInt* 类型 this 指针转换为 const 的 const vectorInt* 类型,目的是为了能够调用 const 重载版本的 at 方法,从而复用其实现逻辑,避免代码重复。
(2)const_cast<int&> 的作用是将 const 版本 at 方法返回的 const int& 类型去除 const 限定,转换为非 const 的 int& 类型,目的是满足非 const 版本 at 接口的契约要求,允许通过返回的引用修改元素值,同时保持与 const 版本实现的一致性。
问题三:
(1)编译器根据对象的const性质选择迭代器重载版本:非const对象v1调用非const版本的begin(),返回可修改的迭代器;const对象v2调用const版本的begin(),返回只读迭代器。非const版本适配需要修改元素的场景,const版本适配只读访问场景,共同保证了类型的const正确性和操作的安全性。
(2)vectorInt直接返回原始指针作为迭代器揭示了迭代器的核心本质是"泛化的指针",它抽象了容器访问的统一接口而非强调实现复杂度。对于连续内存的vector,原始指针天然满足迭代器的所有操作要求,这让我理解到迭代器模式的关键在于提供一致的操作语义,而非实现的复杂性,指针本身就是最简单高效的迭代器实现。
问题四:
使用算法库的这三行更新代码完全可以替代原有实现,它们分别使用 `std::fill_n` 将指定值填充到内存块、使用 `std::copy_n` 复制指定数量的元素到目标内存,这种改写不仅使代码更简洁安全,避免了手写循环可能出现的边界错误,还通过标准库算法的优化提升了可读性和潜在性能,符合C++最佳实践。
实验任务四:
#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'; } task4.cpp
#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; // 数据区 }; matrix.hpp
// matrix.cpp #include "matrix.hpp" #include <iostream> #include <cstdlib> #include <algorithm> // 构造函数:rows_×cols_矩阵,初值value Matrix::Matrix(int rows_, int cols_, double value) : n_rows(rows_), n_cols(cols_), ptr(new double[rows_ * cols_]) { std::fill_n(ptr, n_rows * n_cols, value); } // 构造函数:rows_×rows_方阵,初值value Matrix::Matrix(int rows_, double value) : n_rows(rows_), n_cols(rows_), ptr(new double[rows_ * rows_]) { std::fill_n(ptr, n_rows * n_cols, value); } // 拷贝构造函数:深复制 Matrix::Matrix(const Matrix &x) : n_rows(x.n_rows), n_cols(x.n_cols), ptr(new double[x.n_rows * x.n_cols]) { std::copy_n(x.ptr, n_rows * n_cols, ptr); } // 析构函数 Matrix::~Matrix() { delete[] ptr; } // 按行复制pvalue指向的数据 void Matrix::set(const double *pvalue, int size) { if (size != n_rows * n_cols) { std::cerr << "Error: Size mismatch in Matrix::set\n"; std::exit(1); } std::copy_n(pvalue, size, ptr); } // 矩阵对象数据项置0 void Matrix::clear() { std::fill_n(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 << "Error: Index out of range in Matrix::at\n"; std::exit(1); } return ptr[i * n_cols + j]; } // 返回矩阵对象索引(i,j)对应的数据项引用 double& Matrix::at(int i, int j) { if (i < 0 || i >= n_rows || j < 0 || j >= n_cols) { std::cerr << "Error: Index out of range in Matrix::at\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) { std::cout << at(i, 0); for (int j = 1; j < n_cols; ++j) { std::cout << ", " << at(i, j); } std::cout << '\n'; } }
运行结果为:

实验任务五:
#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; } contact.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(int i = 0;i < contacts.size();i++) { std::string get_name = contacts[i].get_name(); if(name == get_name) return i; } return -1; } // 待补足2:void ContactBook::sort();实现 // 按姓名字典序升序排序通讯录 void ContactBook::sort(){ //使用sort,内部使用lambda表达式对contact类自定义比较 //lambda表达式:[capture](parameters) -> return_type{//函数体(执行逻辑} std::sort(contacts.begin(),contacts.end(),[](const Contact&a,const Contact&b){return a.get_name() < b.get_name();}); } contactBook.hpp
#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(); } task5.cpp
运行结果为:


浙公网安备 33010602011771号