实验三

实验3 类的组合与深拷贝

1. 实验任务1

1.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 <algorithm>
#include <iostream>
#include <string>
#include <vector>

// 窗口类
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;
}

1.2 编译与运行

运行截图:

image

1.3 问题回答

问题1:

Window 和 Button 是组合关系。buttons_ 声明为 Button 的 vector,按值存放 Button 对象,不是 Button 指针,也不是 Button 指针的 vector。这些 Button 对象由 Window 内部的 vector 直接持有,Window 构造函数创建 close 按钮,add_button 直接向 vector 追加对象,外部没有单独持有这些按钮。Window 析构时 vector 析构,其中所有 Button 对象随之析构,按钮的生命期完全由 Window 管理。因此这是强拥有关系的 has-a 组合,不是只保存指针的聚合或关联。

问题2①:

改为公有的优点是外部可以查询某个按钮是否存在,便于调用方在点击前判断,也方便测试。风险是 has_button 原本只是 add_button 和 click_button 的内部辅助函数,公开后会把查找按钮的实现方式暴露成接口的一部分,增加接口面积;调用方可能依赖这一行为,以后把内部存储从 vector 改成 map 时也要维持同样的语义;调用方还可能写出先 has_button 再 click_button 的重复查找代码,产生检查与操作之间的不一致。

问题2②:

决策一个成员函数是 public 还是 private,主要看三点:用户是否真的需要这个操作来完成业务;它是不是仅为内部实现服务;公开后是否容易破坏对象状态或约束。若它是稳定的、用户需要的、语义清晰的高层操作,就设为 public;若它只是内部查找、依赖具体数据结构,或者公开后会让调用方绕过类的整体约束,就保持 private。类的公开接口应尽量小而完整,优先暴露 add、click、display 这类高层行为,把查找细节留在内部。

问题3:

接口 const std::string& get_label() const 返回 const 引用,不产生字符串拷贝,时间是 O(1),内存开销很小,适合频繁读取或字符串较大的场景。但它返回的是对象内部数据的别名,调用方如果把这个引用保存下来,而 Button 被销毁或 label_ 被修改,引用就会悬空;const 只能阻止通过该引用修改内容,不能解决生命期问题。接口 std::string get_label() const 返回 std::string,会发生拷贝,时间和内存都是 O(n),但调用方拿到的是独立对象,不受 Button 生命期影响,也可以自由修改这个副本,安全性更好。这里的 get_label 只读,调用方通常立即使用返回值,所以返回 const 引用更合适;如果调用方需要跨作用域保存标签,或者需要独立的所有权,则应返回值。

问题4①:

程序可以正常运行,输出不变。push_back 先构造一个临时 Button 对象,再把它移动或复制进 vector;emplace_back 把参数直接转发给 Button 的构造函数,在 vector 的元素存储位置上原地构造,少了一次临时对象的构造和析构,也少了一次移动或复制。emplace_back 通常更高效,但可读性略差,参数转发也可能触发非预期的转换;push_back 更直观。

问题4②:

可以,功能等价。std::any_of(first, last, pred) 对 [first, last) 范围内的元素依次调用一元谓词 pred,只要有一个元素使 pred 返回 true,就立即返回 true;如果全部为 false,则返回 false。参数是起止迭代器和谓词,返回值是 bool。这里 lambda 捕获 label,比较 b.get_label() == label,和原来的循环一致,而且找到后会自动短路。

问题4③:

可以,功能等价。std::find_if(first, last, pred) 返回 [first, last) 中第一个使 pred 为 true 的元素的迭代器;如果找不到,返回 last。参数是起止迭代器和一元谓词,返回值是迭代器。这里用返回的迭代器调用 it->click(),找不到时输出提示,和原循环一致。

2. 实验任务2

2.1 源代码如下

task2.cpp

#include <cstddef>
#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);
}

void output1(const std::vector<int> &v) {
    if (v.size() == 0) {
        std::cout << '\n';
        return;
    }

    std::cout << v[0];
    for (std::size_t i = 1; i < v.size(); ++i)
        std::cout << ", " << v[i];
    std::cout << '\n';
}

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';
}

void output3(const std::vector<std::vector<int>> &v) {
    if (v.size() == 0) {
        std::cout << '\n';
        return;
    }

    for (const auto &row : v)
        output2(row);
}

运行截图:

image

2.3 问题回答

问题1:

v1(5, 42) 调用 vector 的 (size_type count, const T& value) 构造,创建大小为 5 的 vector,每个元素初值都是 42。v2(v1) 调用复制构造函数,用 v1 构造 v2,v2 是 v1 的深拷贝。v1 和 v2 都包含 5 个值为 42 的数据项,但两块存储是独立的。

问题2:

v1.size() 是 2,v2.size() 是 2,v1[0].size() 是 3。v1 的两个内层 vector 大小分别是 3 和 4,v2 是 v1 的深拷贝,内层大小同样是 3 和 4。

问题3:

在索引 0 合法的情况下,v1[0] = -1 和 v1.at(0) = -1 效果相同,都会把第一个元素改成 -1。区别在于 operator[] 不做边界检查,越界访问是未定义行为,可能读到垃圾数据或直接崩溃;at 会检查索引,越界时抛出 std::out_of_range 异常,更安全,但有一次边界检查的开销。两者都返回元素的引用,所以都可以放在赋值号左边。

问题4①:

按 auto r = v1[0]; r.push_back(-1); 这种写法,不能。auto 会推导为 int 的 vector,r 是 v1[0] 的一个副本;r.push_back(-1) 只修改这个副本,v1[0] 不受影响。所以如果输出 v1[0],看不到 -1;如果输出 r,r 里面确实会有 -1,但那是另一个对象。要让修改作用到 v1[0],应写成 auto &r = v1[0];。这里的关键是 auto 默认按值推导,只有显式加上 & 才是引用。

问题4②:

写成 const auto &r = v1[0]; 时,r 是引用,不拷贝内层 vector,避免了堆内存的复制,时间和内存开销都更小,适合只读访问。限制是 r 带 const,不能通过它修改元素,也不能调用 push_back;而且引用的生命期依赖 v1[0],如果 v1 被销毁,或者 v1 发生重新分配导致元素地址变化,r 就会悬空。

问题5①:

std::vector 的复制构造函数是深拷贝。v2 复制 v1 后,修改 v1[0] 不会影响 v2;嵌套 vector 也一样,内层 vector 的数据块被分别复制,两个对象完全独立。程序输出中 v1 变成 -1 后 v2 仍然是 42,v1[0] 追加 -1 后 v2[0] 仍然是 1、2、3,这就是深拷贝的直接证据。

问题5②:

当 v 是 int 的 vector 时,v.at(0) 返回 int&,可以修改;当 v 是 const 的 int vector 时,v.at(0) 返回 const int&,只能读。因此 at 必须提供 const 和非 const 两个重载:非 const 版本供普通对象修改元素,const 版本供 const 对象只读访问,同时保持 const 正确性。如果只有非 const 版本,const vector 就无法调用 at;如果 const 对象也返回非 const 引用,就破坏了 const 保护。

3. 实验任务3

3.1 源代码如下

vectorInt.hpp

#pragma once

#include <algorithm>
#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 (int i = 0; i < n_; ++i)
        pdata_[i] = value;
}

inline vectorInt::vectorInt(const vectorInt &vi)
    : n_{vi.n_}, pdata_{new int[n_]} {
    for (int 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 = 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 (int 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);
}

void output1(const vectorInt &vi) {
    if (vi.size() == 0) {
        std::cout << '\n';
        return;
    }

    std::cout << vi.at(0);
    for (int i = 1; i < vi.size(); ++i)
        std::cout << ", " << vi.at(i);
    std::cout << '\n';
}

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';
}

运行截图(待插入):

image

3.3 问题回答

问题1:
更改版本二后运行截图:

image

test3 中执行 x.assign(x),第二次输出 x 时会出现异常:可能输出随机值、0,也可能碰巧仍然是 42,取决于刚释放的内存是否被重新分配并保留了旧内容,不能依赖。原因是版本2先执行 delete[] pdata_,把 x 自己的数据块释放了;随后 n_ = vi.n_,但 vi 就是 x,vi.pdata_ 仍然指向已经被释放的旧块;接着 pdata_ = new int[n_] 可能拿到同一块内存,于是循环里的 pdata_[i] = vi.pdata_[i] 变成用新块(未初始化)给自己赋值,原来的 42 已经丢失,结果是未定义行为。

版本2的缺陷主要有:没有自赋值检查,x.assign(x) 时没有提前返回,导致删除自己的数据后再从自己读取;先释放旧资源,再申请和复制新资源,如果 new int[n_] 抛出 std::bad_alloc,对象会留下指向已释放内存的 pdata_,n_ 也可能已经被修改,析构时再次 delete[] 会造成重复释放;异常安全性不足,分配和复制过程中一旦失败,对象处于不一致状态,不能保证要么成功,要么保持原状;即使不是自赋值,先删除后复制也会让源对象和目标对象在异常情况下更难恢复。安全版本先分配新块、复制完成后再删除旧块、最后更新成员,能提供更强的异常保证。

问题2①:

static_cast<const vectorInt>(this) 把非 const 成员函数中的 this 从 vectorInt 转成 const vectorInt。转换前 this 的类型是 vectorInt,转换后是 const vectorInt*。这样做的目的是调用 const 版本的 at,复用其中的边界检查逻辑,避免在非 const 版本里再写一遍相同的检查代码。因为只是加上 const 限定,不改变对象的实际类型,所以用 static_cast 就够了。

问题2②:

const_cast<int&>(...) 把 const 版本 at 返回的 const int& 转成 int&,去掉 const 限定。转换前的返回类型是 const int&,转换后是 int&。这样非 const 版本的 at 就能把可修改的引用返回给调用方。这个转换只有在原对象确实是普通非 const 对象时才安全;如果对一个真正的 const 对象用这种方式拿到 int& 并修改,就是未定义行为。

问题3①:

vectorInt v1(5); 中 v1 是非 const 对象,调用非 const 的 begin,返回 int,所以 it1 的类型是 int。const vectorInt v2(5); 中 v2 是 const 对象,只能调用 const 的 begin,返回 const int,所以 it2 的类型是 const int。非 const 版本适合需要修改元素的遍历,例如 *it = 10;const 版本适合只读遍历,编译器会阻止通过 it2 修改元素。

问题4:

可以,需要在使用这些算法时包含 algorithm。std::fill_n(pdata_, n_, value) 从 pdata_ 开始,连续写入 n_ 个 value,替代原来的循环赋值,完成构造时的初始化。std::copy_n(vi.pdata_, vi.n_, pdata_) 从 vi.pdata_ 开始复制 vi.n_ 个 int 到 pdata_,替代拷贝构造函数里的循环,完成深拷贝。std::copy_n(vi.pdata_, vi.n_, ptr) 在 assign 中把源对象的 vi.n_ 个数据复制到新分配的 ptr,完成新块的填充;因为 ptr 和旧 pdata_ 是两块不同的内存,复制完成后再删除旧块,逻辑和安全版本一致。这三行都不改变原有语义,只是把显式循环换成了标准算法,代码更简洁,也更不容易写错循环边界。

4. 实验任务4

4.1 源代码如下

matrix.h

#pragma once

// 类 Matrix 声明
class Matrix {
public:
    Matrix(int n_rows, int n_cols, double value = 0);
    Matrix(int n_rows, double value = 0);
    Matrix(const Matrix &x);
    ~Matrix();

    void set(const double *pvalue, int 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 <cstddef>
#include <iostream>
#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: rows and cols must be positive");

    const std::size_t total =
        static_cast<std::size_t>(n_rows_) * static_cast<std::size_t>(n_cols_);
    pdata_ = new double[total];
    std::fill_n(pdata_, total, 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_{nullptr} {
    const std::size_t total =
        static_cast<std::size_t>(n_rows_) * static_cast<std::size_t>(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) {
    const std::size_t total =
        static_cast<std::size_t>(n_rows_) * static_cast<std::size_t>(n_cols_);

    if (size < 0 || static_cast<std::size_t>(size) != total)
        throw std::invalid_argument("Matrix::set: size must be rows*cols");
    if (pvalue == nullptr)
        throw std::invalid_argument("Matrix::set: pvalue must not be null");

    std::copy_n(pvalue, total, pdata_);
}

void Matrix::clear() {
    const std::size_t total =
        static_cast<std::size_t>(n_rows_) * static_cast<std::size_t>(n_cols_);
    std::fill_n(pdata_, total, 0.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::at: index out of range");

    return pdata_[static_cast<std::size_t>(i) * static_cast<std::size_t>(n_cols_) +
                  static_cast<std::size_t>(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) {
            std::cout << pdata_[static_cast<std::size_t>(i) *
                                    static_cast<std::size_t>(n_cols_) +
                                static_cast<std::size_t>(j)];
            if (j + 1 < n_cols_)
                std::cout << ' ';
        }
        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.set(x, n * m);

    Matrix m2(m, n);
    m2.set(x, m * n);

    Matrix m3(n);
    m3.set(x, n * n);

    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);
}

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';
}

运行截图:

image

4.3 问题回答

问题1:

set(const double pvalue, int size) 只能检查 size 是否等于矩阵的 rowscols,它无法知道 pvalue 实际指向的数组有多长。长度信息完全依赖调用者传入的 size,调用者可以传一个和真实数组长度不符的值,set 仍然会按这个 size 去读,造成越界访问。

测试中把数组改成 double x[5] = {1, 2, 3, 4, 5}; 后,如果输入 2 3,nm 是 6,set(x, 6) 会读取 x[0] 到 x[5],其中 x[5] 已经越界;如果输入 2 5,nm 是 10,会读取 10 个元素,越界更严重。结果可能打印出垃圾值,也可能直接崩溃,属于未定义行为。原测试用 double x[1000] 只是为了数组足够大掩盖了这个问题,并不代表接口安全。

优化的核心是让数据长度跟随数据一起传递,而不是让调用者单独报一个可能撒谎的 size。C++17 下可以把接口改成接受 double 的 const vector 引用,函数内部用 values.size() 校验并 std::copy(values.begin(), values.end(), pdata_);也可以用 std::array 的模板引用,让数组长度成为类型的一部分。C++20 可以用 std::span(元素为 const double),它同时携带指针和长度,是更现代的做法。如果必须保留指针接口,至少要在文档中明确 pvalue 至少要有 size 个元素的前置条件,并在调试版本加断言;但这仍然不能从根本上防止调用者传错长度。

5. 实验任务5

5.1 源代码如下

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 <cstddef>
#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;
    std::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 (const auto &c : contacts_) {
        c.display();
        std::cout << '\n';
    }
}

inline std::size_t ContactBook::size() const {
    return contacts_.size();
}

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", "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

posted @ 2026-11-26 17:28  TDTTDT  阅读(2)  评论(0)    收藏  举报