实验3
实验任务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();
return 0;
}
button.cpp:
#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.cpp:
#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;
}
测试截图如下:

问题1:
是组合关系。
button的类型是std::vector<button>,保存的是button对象的值,不是指针。
生命周期:二者生命周期完全绑定,符合组合的定义。
问题2:
①: 优点:外部代码可以直接调用has_button,提前查询某个按钮是否存在,不用自己遍历按钮列表。
风险:该函数只是内部辅助判断,不属于窗口对外核心功能,开放后增加类的接口负担,破坏封装.
②:public:是类对外提供的服务接口,外部用户需要调用、并且是类承诺稳定提供的能力;
private:用户不需要直接调用,只给类内部其他成员函数使用;
原则:凡是调用后有可能破坏对象内部状态、或者只是实现中间步骤的函数,一律private;只把用户必须用到的操作开放为 public。
问题3:
接口1:
性能:更好,直接返回内部成员字符串的常量引用,不拷贝内存,没有字符串复制开销;
安全:返回 const 引用,外部不能通过这个引用修改类内部的成员,不会破坏button内部状态;
接口 2:
性能:需要拷贝一份string,字符串长的时候开销更大;
安全:更安全,返回的是独立副本,副本和原对象完全分离,就算原button销毁,副本也可以正常使用,不存在悬空引用风险。
总结:接口 1 零拷贝、高效,但存在悬空引用风险;接口 2 有拷贝开销,但是生命周期安全。
问题4:
①:程序可以正常运行。
p:先在外部临时构造一个Button临时对象,再把这个临时对象拷贝进 vector 容器;
e:直接在 vector 容器内部的内存空间原地构造button对象,省去临时对象的构造、移动开销,效率更高。
②写法合法,可以正常运行。
参数:first,last是迭代器范围;pred是判断谓词
返回值:范围内任意一个元素满足,返回true;全部满足,返回false。
③:可以正常运行
参数:迭代器范围 + 谓词
返回值:返回第一个满足元素的迭代器,找不到则返回end。 拿到迭代器后判断是否等于end,找到就调用click,找不到输出提示,和原逻辑一致。
问题5:
上百个按钮时,一般不会成为瓶颈;但如果按钮数量达到几千上万,每次点击都从头到尾遍历,查找耗时会明显上涨,成为性能瓶颈。
如果改用std::存储按钮:原来display是按添加顺序依次输出按钮;改成map之后,输出会按照label字符串字典序排序输出,不再是添加顺序。
是否可接受:可以。
实验任务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();
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(auto 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:
std::vector<int> v1 (5, 42) 调用构造函数,创建vector。
const std::vector<int> v2 (v1) 调用拷贝构造函数,用 v1 拷贝构造 v2。
v1 包含 5 个,v2 包含 5 个。
问题2:
v1.size() = 2 v2.size() = 2 v1[0].size() = 3
问题3:
能达到一样的效果。
operator不做越界检查,越界后为未定义行为,运行速度更快。 .at自带越界检查,下标越界会抛出std::out_of_range异常,安全性更高。
问题4:
①:可以。 原因:v1 [0] 返回内层 vector 的引用,r 绑定到原内层 vector 对象;v1 [0].push_back (-1) 修改原容器,r 指向同一个容器,因此可以读到新增元素 - 1。
②:优势:const &只是绑定引用,不会拷贝整个vector,节省内存与拷贝开销。 限制:无法通过 r 修改容器内元素;r 的生命周期不能超过原 vector,否则会产生悬空引用。
问题5:
①:深拷贝。
②:int&,可读可写;const int&,只读。
结论:std::vector 的 at () 必须提供 const 重载版本,根据容器是否为 const,返回对应权限的引用,保证 const 容器不能被修改。
实验任务3:
#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_;
}
#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:
运行截图:

当 test3 中执行x.assign(x)发生对象自我赋值时,程序会出现异常。
安全隐患与缺陷:
缺少自赋值判断。 先释放旧内存,再申请新内存。
原安全版本会先申请新内存,数据拷贝完成后再释放旧内存。即便 new 抛出异常,原对象的数据不会丢失;同时处理自赋值情况。版本 2 缺失这两层保护。 运行 test3 模块执行x.assign(x),会出现程序崩溃或者输出随机乱数。
问题2:
①转换前 this 的类型:指向可修改的普通对象。 转换后 this 的类型:为对象指针增加 const 修饰。
作用:将当前对象指针视作 const 对象指针。 转换目的:调用 const 版本的 at () 函数,复用其中的下标越界检查逻辑,避免重复书写边界判断代码。
②转换前返回值类型:来自 const 版本 at () 的返回值,为只读常量引用。 转换后返回值类型:可读可写普通引用。
作用:移除返回引用上的 const 限定。 转换目的:非 const 版本 at 需要返回可修改的引用;此处原对象本身不是 const,去除 const 限定是安全合法。
问题3:
编译器根据调用对象是否为 const 来选择重载版本: 非 const 对象调用 begin (),匹配非 const 成员函数,返回普通指针int*;适配场景:需要通过迭代器修改容器内元素。 const 对象调用 begin (),只能调用带 const 修饰的成员函数,返回const int*;适配场景:只读遍历容器,禁止修改容器元素,保证 const 对象数据不会被修改。
②vectorInt 直接返回原生指针充当迭代器,让我理解迭代器本质是对访问位置的抽象,原生指针本身就具备迭代器的基础语义,可以作为最简迭代器。迭代器不一定是复杂的类封装;对于连续内存的容器,原生指针支持自增、解引用、比较等迭代器操作。标准库 std::vector 的迭代器在部分编译器底层就是对原生指针做封装。
问题4:
三处修改均可以正常工作.
更新1; 功能:从 pdata_起始位置开始,对后续 n_个元素全部赋值为 value,替代手写 for 循环,完成动态数组的批量初始化。
更新2; 功能:从源地址 vi.pdata_复制 n_个元素到目标地址 pdata_,替代手写循环,完成拷贝构造函数的数据深拷贝。
更新3; 功能:将 vi 对象内部 n_个数据复制到新申请的 ptr 内存,替代 assign 内部手写循环,完成 assign 的数据拷贝。
std::fill_n 用于批量填充同一个数值;std::copy_n 用于整块内存原样复制。使用算法库替代手写循环,代码更加简洁,标准库算法也经过性能优化。
实验任务4:
#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_; // 数据区
};
#include "matrix.h"
#include <algorithm>
#include <iostream>
#include <stdexcept>
Matrix::Matrix(int n_rows, int n_cols, double value)
: n_rows_{n_rows}, n_cols_{n_cols}, 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_;
int total = n_rows_ * n_cols_;
pdata_ = new double[total];
std::copy_n(x.pdata_, total, 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");
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];
}
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 << at(i, j);
}
std::cout << '\n';
}
}
#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';
}
运行截图:(输入2,5)

接口的设计与测试模块,存在潜在风险。
当数组实际长度小于传入的 size 参数,但调用 set 传入更大的 size 值,此时指针会访问数组后面不属于该数组的内存空间,发生越界读取,属于未定义行为,程序会读到脏数据。set 仅做 size 与矩阵元素数量相等的判断,无法校验传入的原始数组实际内存长度,指针本身不携带数组长度信息。
优化方案:
不直接接收裸指针,改用std::spam<double>接收数据,span 同时记录指针与有效长度,编译器可以做边界检查。
实验任务5:
#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_;
}
#pragma once
#include "contact.hpp"
#include <algorithm>
#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;
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();
}
inline int ContactBook::index(const std::string &name) const {
for(int i = 0; i < static_cast<int>(contacts_.size()); i++) {
if(contacts_[i].get_name() == name) {
return 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();
});
}
#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();
}
运行截图:

回答问题(拓展思考):
现有通讯录基础上迭代扩展功能,要保持原有对外接口不变,只新增成员函数,不修改已有的 add、remove、find、display 等对外接口,保证旧代码可以继续运行。
修改联系人功能:新增modify功能,私有借助 index () 找到下标,修改对应 Contact 内部 phone_。
数据有效性校验:在 add 函数内部增加校验,判断姓名、手机号不为空,手机号字符格式合法性,非法则输出提示,拒绝添加。
异常处理:手机号格式错误、传入空字符串抛出异常或者返回状态提示。
数据持久化存储:增加save功能和load功能,把 contacts_序列化写入文本文件,程序启动时读取文件恢复联系人数据。
高阶功能
联系人分组:新增 Group 类,ContactBook 增加std::vector<group>成员;
模糊检索:新增find功能,遍历 contacts_匹配姓名包含关键词的联系人并输出。
内部工具函数可以持续扩充,对外公开接口尽量兼容旧版本,实现代码逐步迭代扩展。
五:实验总结
收获经验:
使用原始指针管理堆内存时,要重点关注拷贝构造、赋值运算符、析构函数三部分,注意自我赋值、内存分配失败异常安全问题;优先选用标准容器代替裸指针,减少手动内存管理。
类的成员函数合理区分public与private,对外只暴露必要接口,实现细节尽量私有封装。const 修饰要合理使用,保护只读对象不被意外修改,配套提供const重载成员函数。
标准库算法std::any_of、std::find_if、std::copy_n可以替代手写循环,代码简洁,同时需要熟悉迭代器的传入与返回值。
做类设计时,预留后续扩展空间,尽量不修改已对外公开的接口,新增功能通过新增成员函数实现,维持代码可维护性。
浙公网安备 33010602011771号