实验3 类和对象
四、实验结论
实验任务 1 · 窗口和按钮
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_.emplace_back("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 {
return std::any_of(buttons_.begin(), buttons_.end(),
[&label](const Button &button) { return button.get_label() == label; });
}
inline void Window::add_button(const std::string &label) {
if(has_button(label))
std::cout << "button " << label << " already exists!\n";
else
buttons_.emplace_back(label);
}
inline void Window::click_button(const std::string &label) {
auto it = std::find_if(buttons_.begin(), buttons_.end(),
[&label](const Button &button) { return button.get_label() == label; });
if (it != buttons_.end())
it->click();
else
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;
}

问题 1 是组合关系。Window 通过 vector<Button> 按值保存按钮,窗口析构时,容器里的按钮也会被销毁。
问题 2 公开 has_button() 方便调用者提前查询,也会让外部代码依赖当前的标签匹配规则。外部需要、能保护对象状态的操作可以公开,内部辅助函数适合设为私有。本例由 add_button() 负责查重。
问题 3 返回 const string& 可以省掉字符串复制,原对象失效后引用也不能再用。按值返回需要复制,但得到的字符串可以独立使用。
问题 4 改写后运行结果相同。push_back(Button(label)) 先构造临时对象,再移动进容器。emplace_back(label) 在容器里直接构造。any_of(first, last, pred) 判断区间内是否至少有一个元素符合条件,返回布尔值。find_if(first, last, pred) 返回第一个符合条件的元素迭代器,找不到就返回 last。
实验任务 2 · 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.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:\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(std::vector<int>::size_type 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 v1(5, 42) 构造五个值为 42 的元素,v2(v1) 调用拷贝构造,拷贝后两者各有五个 42。
问题 2 两个外层 vector 的大小都是 2,v1[0].size() 是 3。追加 -1 后,v1[0] 的大小变为 4,v2[0] 仍为 3。
问题 3 v1.at(0) = -1 的结果相同。at() 越界会抛出 std::out_of_range,下标运算符 [] 要求下标有效。
问题 4 能输出 -1。r 引用追加过元素的 v1[0],最后一项就是 -1。const & 省去内层容器的复制,通过它只能读,原对象失效后不能再用。
问题 5 本例是深拷贝,改动 v1 后 v2 保持原样。非常量 vector<int> 的 at() 返回 int&,常量对象调用 const 重载,得到 const int&。
实验任务 3 · 自定义 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';
}

问题 1 安全版自赋值前后都输出五个 42。版本 2 这次自赋值后输出 0, 0, 0, 0, 0。它没判断自赋值,先释放旧数组,丢掉了原来的值。重新分配后,源和目标指向同一个刚分配的数组,复制时读到的是未初始化的 int,每次结果可能不同。如果分配失败,旧内存已经释放,留下的指针还可能被析构函数再次释放。

问题 2 非 const 函数里的 this 是 vectorInt*。转成 const vectorInt* 后会调用 const 版 at(),复用越界检查。再用 const_cast<int&> 把返回的 const int& 转成 int&,让非常量对象仍可修改元素。
问题 3 v1.begin() 选非 const 版本,得到可读写元素的 int*。v2.begin() 选 const 版本,得到只能读取元素的 const int*。end() 的选择规则一样,返回尾后位置。
问题 4 可以。fill_n 给指定数量的元素填同一个值。拷贝构造中的 copy_n 把数据复制到新对象的数组,assign() 里的 copy_n 先复制到临时数组,再替换原数组。改写版也用 n = 6 跑过,输出和安全版相同。
参考 C++ 算法条款和 C++ 类型转换条款。
实验任务 4 · 矩阵类
matrix.h
#pragma once
// 类 Matrix 声明
class Matrix {
public:
Matrix(int n_rows, int n_cols, double value = 0); // 构造 n_rows*n_cols 矩阵
Matrix(int n_rows, double value = 0); // 构造 n_rows*n_rows 方阵
Matrix(const Matrix &x); // 拷贝构造(深拷贝)
~Matrix();
void set(const double *pvalue, int size); // 按行复制,size 必须等于元素总数
void clear(); // 所有元素置零
const double& at(int i, int j) const;
double& at(int i, int 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 <iostream>
#include <limits>
#include <stdexcept>
Matrix::Matrix(int n_rows, int n_cols, double value)
: n_rows_{n_rows}, n_cols_{n_cols}, pdata_{nullptr} {
if(n_rows <= 0 || n_cols <= 0)
throw std::invalid_argument("matrix dimensions must be positive");
if(n_rows > std::numeric_limits<int>::max() / n_cols)
throw std::length_error("too many matrix elements");
const int size = n_rows * n_cols;
pdata_ = new double[size];
std::fill_n(pdata_, size, 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");
if(pvalue == nullptr)
throw std::invalid_argument("pvalue must not be null");
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("matrix index out of range");
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) {
std::cout << at(i, 0);
for(int j = 1; j < n_cols_; ++j)
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';
}

输入 2 5。清空并修改 m1 后,第一行是 1, 2, 0, 0, 0,m2 的第一行仍全是 -1,说明两个矩阵的数据是独立的。
问题 set() 检查的是传入的数量,指针本身不带数组长度。把 x 缩成五项后,输入 2 3 或 2 5,前两个矩阵仍分别会读六项或十项,造成越界读取。可以用数组引用模板拿到实际长度,再检查实际长度至少覆盖要复制的元素数,同时检查复制数量等于矩阵容量。
实验任务 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.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();
}
// 返回联系人在 contacts 内索引 ; 如不存在,返回 -1
inline int ContactBook::index(const std::string &name) const {
for(std::size_t i = 0; i < contacts_.size(); ++i) {
if(contacts_[i].get_name() == name)
return static_cast<int>(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();
});
}
task5.cpp
#include "contactbook.hpp"
void test() {
ContactBook contactbook;
std::cout << "1. add contacts\n";
contactbook.add("Bob", "00000000001");
contactbook.add("Alice", "00000000002");
contactbook.add("Linda", "00000000003");
contactbook.add("Alice", "00000000002");
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();
}
下面的运行记录和博文源码用占位号码展示,查找、排序和删除逻辑与测试一致。

联系人按 Alice、Bob、Linda 的顺序显示。重复添加 Alice 会提示失败,查找和删除不存在的 David 也有提示。删除 Bob 后剩两人。
使用了ai辅助整理实验结果和排版网页。

浙公网安备 33010602011771号