实验3
任务1
- window.hpp源代码
点击查看源代码
#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;
}
- 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_;
};
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";
}
- 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;
}
- 运行截图

- 问题回答
- 是组合关系。buttons_是std::vector<Button>(值类型存储,不是指针),Button 对象直接在 vector 内部分配;Window 生命周期结束时,vector 自动销毁,内部所有 Button 对象同步销毁,Button 不能脱离 Window 独立存在,符合组合的特征。
- (1) 如果改为 public:优点:外部代码可以直接调用has_button查询按钮是否存在,外部使用更灵活;
风险:暴露内部查询逻辑,外部频繁调用会依赖内部实现;后续如果修改内部容器结构(vector 改别的容器),外部代码可能受影响;破坏封装,不必要地开放内部细节。
(2) 判定规则:
public:类的外部用户需要调用,属于对外提供的核心功能;
private:仅类内部其他成员函数需要调用,属于内部实现细节,对外不需要暴露;开放后不会给外部带来必要价值,还容易暴露内部结构、允许外部随意检查内部状态,破坏封装。 - (1) 接口 1:const std::string& get_label() const;
性能:返回引用,不拷贝字符串,开销小;
安全:const 引用,外部不能修改内部label_,安全。
(2) 接口 2:std::string get_label() const;
性能:返回值,会拷贝一份字符串,有内存拷贝开销;
安全:返回副本,外部修改副本完全不影响对象内部成员,安全性也可靠,但性能更差。 - (1)修改后程序可以正常运行。
push_back(Button(xxx)):先在外部创建临时 Button 对象,再把临时对象拷贝进 vector;
emplace_back(xxx):直接在 vector 容器内部原地构造 Button 对象,省去临时对象的拷贝,效率更高。
(2)这段代码写法合法,可以运行。
std::any_of(first, last, pred):遍历[first,last)区间,只要任意一个元素满足谓词 pred 返回 true,整体返回 true;全部不满足返回 false。
参数:首迭代器、尾后迭代器、判断谓词(lambda / 函数);返回 bool。
(3)这段代码写法合法,可以运行。
std::find_if(first, last, pred):遍历区间,找到第一个满足谓词 pred 的元素,返回指向该元素的迭代器;找不到返回尾后迭代器end()。
参数:首迭代器、尾后迭代器、判断谓词;返回迭代器。
任务2
- task2.cpp源代码
点击查看源代码
#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);
}
- 运行截图

- 问题回答
- std::vector
v1(5, 42);:参数化构造(填充构造),创建 vector,包含 5 个元素,全部初始化为 42。
const std::vectorv2(v1);:复制构造,用 v1 拷贝生成 v2。
v1:5个42;v2:5个42。 - v1.size()=2; v2.size()=2; v1[0].size()=3
- 可以实现同等赋值效果。区别:
- v1[0]:下标运算符,不做越界检查,下标非法时直接未定义行为,程序可能崩溃;速度快。
- v1.at(0):带边界检查,下标越界会抛出std::out_of_range异常,安全性更高但开销大。
- (1)可以输出 - 1。const std::vector
&r=v1[0];是引用,绑定到 v1 里面第一个子 vector;v1[0].push_back(-1)之后,这个子 vector 末尾新增 - 1,r 依然指向它,r[r.size()-1]访问到新增的 -1。
(2)优势:不拷贝整个 vector,只建立引用,节省内存、避免拷贝耗时;限制:const &不能通过 r 修改容器内元素;r 的生命周期不能超过原容器 v1,原容器销毁后引用失效。 - (1)vector 的复制构造是深拷贝:复制之后两个 vector 拥有独立的数据缓冲区,修改其中一个不会影响另一个。验证:修改 v1 元素,v2 不会跟着变。
(2)vector:v.at(0) 返回 int&;const vector v:v.at(0) 返回 const int&;
必须提供 const 重载版本:const 容器只能调用 const 成员函数,保证 const 对象不能通过 at 修改内部元素,符合 const 语义。
任务3
- task3.cpp源代码
点击查看源代码
#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';
}
- vectorInt.hpp源代码
点击查看源代码
#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_;
}
- 运行截图

- 问题回答
- 异常现象:自赋值的时候,先 delete [] pdata_,vi 和 this 是同一个对象,vi.pdata_已经被释放,后续拷贝时访问已经释放的内存,产生未定义行为,程序崩溃。
安全隐患:
(1)没有自赋值判断:x.assign(x) 自赋值场景下先释放自身内存,源数据被销毁,拷贝非法内存。
(2)内存释放和分配顺序风险:释放旧内存之后才分配新内存,如果new抛出异常,pdata_变成野指针,对象处于非法状态。 - (1)static_cast<const vectorInt>(this)
转换前:this 是 vectorInt(普通、可修改指针)
转换后:const vectorInt*
作用:把当前对象指针转为 const 版本指针,强制调用 const 重载的 at(),避免无限递归。
目的:复用 const 版 at 的边界检查逻辑,不用重复写一遍越界判断。
(2)const_cast<int&>(...)
转换前返回值:const int&(const 引用,不可修改)
转换后返回值:int&(普通引用,可以修改)
作用:去掉 const 修饰。
目的:const 版 at 返回只读引用,去掉 const 之后,让非 const 的 at 接口返回可修改引用;前提是保证对象本身是非 const,安全。 - (1)非 const begin/end:用于可修改对象,迭代器允许修改容器内元素;
(2)const begin/end:用于const 对象,迭代器只读,不能修改元素,保证 const 语义。 - (1)std::fill_n(pdata_, n_, value);:从起始地址pdata_开始,连续填充 n_ 个 value,替代循环赋值。
(2)std::copy_n(vi.pdata_, vi.n_, pdata_);:从源地址vi.pdata_复制 vi.n_ 个元素,写入目标地址pdata_,替代拷贝循环。
(3)std::copy_n(vi.pdata_, vi.n_, ptr);:先把源数据拷贝到新开辟的内存块 ptr,等拷贝完成、确认没问题之后,再释放旧内存、替换指针,保证异常安全,和原本安全版 assign 逻辑一致。
任务4
- task4.cpp源代码
点击查看源代码
#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';
}
- matrix.cpp源代码
点击查看源代码
#include "matrix.h"
#include <algorithm>
#include <cstdlib>
#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_;
pdata_ = new double[n_rows_ * n_cols_];
std::copy_n(x.pdata_, n_rows_ * n_cols_, 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];
}
// 返回矩阵对象索引(i,j)对应的数据项引用(越界则抛出异常)
// 参考前一个接口和task3的问题2
double& Matrix::at(int i, int j) {
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];
}
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 << pdata_[i * n_cols_ + j];
}
std::cout << "\n";
}
}
- matrix.h源代码
点击查看源代码
#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_; // 数据区
};
-
运行截图
![image]()
-
问题回答
(1)风险分析
该接口void set(const double *pvalue, int size);存在潜在风险。
pvalue只是裸指针,接口无法知道传入数组实际的长度,仅靠传入的size参数来控制拷贝数量。
当数组改成double x[5] = {1,2,3,4,5};,如果输入参数要求size=10(例如输入 2 5,矩阵需要 10 个元素),指针仍然可以正常传递,编译器不会报错。程序会从 x 的内存向后越界读取数组之外的内存(内存越界访问),读取到随机垃圾值,属于未定义行为,出现程序崩溃。
(2)优化方案:改用std::span接收参数,span 自带源缓冲区长度信息,接口内部可以同时校验源长度≥需要拷贝的元素数量,从根源上防止越界读。
任务5
- contact.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_; // 必填项
};
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_;
}
- contactbook.cpp源代码
点击查看源代码
# 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; // 返回联系人在vector内索引,如不存在,返回-1
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();
}
//int index(const std::string &name) const;实现
// 返回联系人在contacts内索引; 如不存在,返回-1
inline 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;
}
//void ContactBook::sort();实现
// 按姓名字典序升序排序通讯录
inline void ContactBook::sort()
{
std::sort(contacts_.begin(), contacts_.end(), [](const Contact &a, const Contact &b)
{
return a.get_name() < b.get_name();
});
}
- 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");
std::cout << "\n5. display contacts\n";
std::cout << "There are " << contactbook.size() << " contacts.\n";
contactbook.display();
}
int main() {
test();
}
- 运行截图
![image]()
实验总结
在实验中我实践了类与封装,将数据和成员函数封装,隐藏内部实现,仅通过接口访问数据;掌握构造函数、委托构造、深拷贝,理解浅拷贝会造成内存重复释放的风险,学会动态内存管理防止内存泄漏。学习了 const 修饰成员函数、函数重载,区分只读与可写接口,运用异常机制处理越界、参数不匹配等错误。同时体会到裸指针接口存在越界读取隐患,了解现代 C++ 安全接口设计思路,还练习了组合关系、vector 容器、排序与查找等。通过实验,我认识到面向对象的核心是封装、职责划分,对象自主管理自身状态与资源,代码结构清晰、易于维护,提升了程序健壮性与可扩展性。



浙公网安备 33010602011771号