实验3
任务一 组合类 Window 和 Button
源代码
点击查看代码
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";
}
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;
}
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;
}
运行截图

问题
-
属于组合关系。Window 内部有一个 vector
-
① 公开以后外部代码可以直接查询某个按钮在不在,不必自己再遍历一遍;代价是内部实现被固定下来,以后调整存储方式会影响所有调用方,而且外部可以绕过 add_button 直接动容器,按钮重复、顺序错乱这类问题就不好约束了。
② 我主要看三点:外部有没有真实需要(有就倾向公开);是不是只为本类其他方法服务(是就隐藏);调用后会不会让对象进入不一致状态(会就隐藏)。按这个标准,add_button、click_button、display 是给使用者用的,has_button 只是前两个方法的辅助,外部自己遍历也能实现,放私有区更合适。
-
接口1 返回引用,函数返回时不产生字符串副本,长字符串时差别明显;因为带了 const,调用方只能读不能写,对象内部的数据不会被改掉。接口2 返回的是值,每次调用都复制一份,调用频繁时有开销;好处是调用方拿到的是独立副本,怎么改都不影响原对象。这里只需要让外部看到按钮文字,接口1 更贴合。
-
① 可以正常运行,输出与原来一模一样。差别在对象怎么产生:push_back 接收的是已经构造好的 Button,容器内部还要再拷贝或移动一次;emplace_back 把参数直接转发到容器的内存上就地构造,省掉临时对象。
② 可以。any_of 把区间里的元素依次交给判断函数,只要有一个让它返回 true 就立即结束并返回 true,全部试完还是 false 就返回 false。has_button 要回答的就是“存不存在”,语义一致,所以能直接替换。
③ 可以。find_if 与 any_of 的区别在返回值,它返回指向第一个满足条件元素的迭代器,没有就返回 end()。改写时要判断 it != buttons_.end(),成立就调用 it->click(),否则输出找不到的提示。
- 选做。按钮到几百个时,每次点击都要顺序扫描一遍,代价是 O(n),点得频繁会拖慢响应;不过常见的工具窗口按钮数量有限,实际感觉不明显。换成 map 后查找降到 O(log n),但 map 的遍历顺序由 key 决定,display() 会变成字母序输出,和用户在界面上看到的排列对不上,我认为这个代价偏大。折中的做法是保留 vector 负责顺序和显示,另外维护一个 name 到索引的 map 专门用于查找。
任务二 标准库 vector 的深拷贝
源代码
点击查看代码
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);
}
运行截图

问题
-
第一行是“指定大小并给初值”的构造,一次性填入 5 个 42;第二行是拷贝构造,用 v1 的内容初始化新的 vector。结果是 v1 与 v2 各含 5 个值为 42 的元素,并且各占一块内存。
-
两个外层 vector 都含 2 个元素,所以 v1.size() 与 v2.size() 都是 2;此时 v1[0] 还是 {1, 2, 3},长度为 3。
-
可以,效果相同。区别在检查:[] 不做下标检查,越界属于未定义行为,可能读到别的变量甚至崩掉;at() 会检查,越界抛 std::out_of_range,异常能定位到出错的位置。开发阶段建议用 at(),确认安全后再换回 []。
-
① 要看这两行访问的是哪个对象。访问 v1[0] 能打印出 -1,因为这个内层 vector 确实被 push_back 改过;访问 v2[0] 打印不出来,v2 是 v1 的深拷贝,两份数据互不影响。
② 用 const 引用承接返回值,等于给内层 vector 起个别名,不复制元素,元素多时省内存也省时间。限制有两条:不能通过它修改元素;它与 v1[0] 绑定,v1 销毁或内层 vector 重新分配内存后就失效了。
- ① 是深拷贝。理由很直接:对 v1 的元素做了修改,v2 的内容没有任何变化,说明两者不共享数据。
② 非 const 对象调用返回 int&,const 对象调用返回 const int&。const 版本不能省:const 对象的 this 是 const 指针,只能调用 const 成员函数,缺了这个重载,const 对象连读取都编译不过。
任务三 自定义 vectorInt 与深拷贝
源代码
点击查看代码
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_;
}
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';
}
运行截图


问题
-
换成版本2 后,前两个测试模块正常,第三个模块 x.assign(x) 的结果明显不对,输出变成 -1790284576, 464 一类数字,换环境跑还可能直接崩。原因有三处:一是删掉了 this == &vi 的判断,自己赋值给自己时形参和对象是同一块内存;二是执行顺序变成 delete[] 再复制,复制时源指针指向的正是刚释放的内存,读到的是已经归还给系统的数据;三是 new 排在 delete 之后,一旦 new 抛异常,pdata_ 已失效而 n_ 已改,成员之间不再一致。原版本先用临时指针申请并复制,成功后才释放旧内存,这三个问题都不存在。
-
① static_cast<const vectorInt>(this) 实际是给 this 加 const:转换前 this 的类型是 vectorInt,转换后是 const vectorInt*。加了 const 才能匹配到 const 版的 at(),从而复用其中的越界检查,非 const 版本只留一行转发。
② const_cast<int&> 是去掉 const:转换前返回类型是 const int&,转换后是 int&。因为 const 版 at() 返回的是只读引用,而非 const 版要对外提供可写引用,只能把 const 去掉;前提是这个对象本身不是 const 对象。
- ① it1 来自非 const 对象 v1,编译器选非 const 重载,类型是 int;it2 来自 const 对象 v2,只能选 const 重载,类型是 const int。前者用于需要写入的遍历,比如初始化元素;后者用于只读场合,比如输出函数以 const 引用接收对象时。
② 选答。这里直接把 int* 当迭代器,说明迭代器本身并不神秘,“取当前元素、移到下一个、判断是否到末尾”这几件事指针天生就会做,所以能直接充当。换成链表这类内部是节点的容器就不行,但使用者的写法不变,这正体现了迭代器把容器内部结构和遍历方式隔开了。
- 可以,三处替换都等价。fill_n(pdata_, n_, value) 用 value 填充前 n_ 个位置;copy_n(vi.pdata_, vi.n_, pdata_) 从源内存复制指定个数;assign 里则复制到临时申请的 ptr。写法更短,也不用自己维护循环变量,少一类下标错误。
任务四 动态矩阵类 Matrix
源代码
点击查看代码
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_; // 数据区
};
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[x.n_rows_ * x.n_cols_]} {
for(int i = 0; i < n_rows_ * n_cols_; ++i)
pdata_[i] = x.pdata_[i];
}
// 析构:回收数据区
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];
}
// 非const版本:同样的范围检查,返回可修改的引用
double& Matrix::at(int i, int j) {
if(i < 0 || i >= n_rows_ || j < 0 || j >= n_cols_)
throw std::out_of_range("row or column index out of range");
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 << at(i, j);
}
std::cout << '\n';
}
}
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';
}
运行截图

问题
这组接口和测试代码放在一起是有隐患的。set() 只把 size 与 n_rows_*n_cols_ 比较,对 pvalue 所指数组的真实长度一无所知;测试里原来的数组给了 1000 个元素,正好掩盖了这一点。把数组改成 double x[5],再输入 2 5,size 仍然是 10,检查通过,copy_n 却要读 10 个 double,后 5 个落在数组之外,读到的是栈上的残留数据,于是打印出 6.9516e-310 这类结果。程序不报错也不警告,这类问题最难排查。
改进方向:让接口自己带上长度信息,比如形参改成 const std::vector
拓展:把 double* 换成 std::vector
任务五 简化版通讯录 ContactBook
源代码
点击查看代码
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.hpp
# 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();
}
// 待补足1:按姓名查找,命中返回下标,否则返回 -1
inline int ContactBook::index(const std::string &name) const {
int i = 0;
for(const auto &c: contacts_) {
if(c.get_name() == name)
return i;
++i;
}
return -1;
}
// 待补足2:按姓名字典序升序排序
inline void ContactBook::sort() {
auto by_name = [](const Contact &a, const Contact &b) {
return a.get_name() < b.get_name();
};
std::sort(contacts_.begin(), contacts_.end(), by_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();
}
运行截图

问题
index():遍历 contacts_,逐个用 get_name() 和形参比较。std::string 的 == 是逐字符比较,所以查找区分大小写,符合题目要求。命中就返回当前下标,遍历完仍未命中返回 -1,调用方据此判断存在与否;返回值用 int 而不是 size_t,就是为了能用 -1 表示未找到。
sort():调用 std::sort,比较规则写成 lambda,按 get_name() 的字典序升序。add() 在插入成功后立即调用 sort(),contacts_ 始终保持有序,display() 和 find() 的输出顺序也就固定了。
拓展:可以继续加修改联系人(先用 index() 定位再改电话)、手机号格式校验、写入文件做持久化,再往后能做分组和模糊查询。扩展时保持公有接口不变,新功能另加方法,原有测试代码就不用改。
总结
这次实验把类的组合、深拷贝和标准库串了一遍。任务一第一次把两个类真正搭在一起用,才看清楚对象的创建和销毁是跟着外层走的,不用手动 delete;也理解了为什么有些方法必须藏在私有区,接口开太多后面改起来很麻烦。
任务二和任务三讲的是同一件事的两个侧面。用标准库 vector 时,深拷贝是它自动完成的,改一个不影响另一个;自己动手写 vectorInt,才把“重新申请内存、再逐项复制”这套动作走了一遍。assign 两个版本只差几行,版本2 在自赋值时会读到已释放的内存,输出直接变成随机数字,比看文字说明印象深得多。
任务四、任务五更接近综合应用。Matrix 让我注意到接口设计的盲点:set() 只凭 size 参数判断,调用方给的数组不够长时照样能通过,程序不报错但结果全错,这种问题最难查。通讯录代码量不大,但补的两个工具函数必须和已有代码的约定吻合,比如 sort() 要在 add() 之后调用,index() 返回 -1 的语义要和 remove()、find() 对上。
还有一个体会是标准库用得多,手写代码就少,出错机会也少。fill_n、copy_n、any_of、find_if、sort 都能替掉一段循环,短而且清楚。后面想再练练异常安全和 RAII,比如把 Matrix 改成用 vector 存数据,对比两种写法。
浙公网安备 33010602011771号