实验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_.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;
}

截图

image

问题1:这个范例中, Window 和 Button 是组合关系吗?结合成员 buttons_ 的声明方式(值还是指针)和对象生命周期的管理方式来回答。:

Window 和 Button 是典型的组合(has-a)关系。

  • 成员 buttons_ 是 std::vector<Button> 值类型,而非指针类型,Button 对象直接存储在 Window 的内存空间中。
  • 生命周期完全绑定:Window 对象构造时,内部的 Button 成员随之构造;Window 对象销毁时,vector 会自动析构所有 Button 对象,Button 的生命周期完全从属并依赖于 Window 对象,符合组合关系的特征。

问题2: bool has_button(const std::string &label) const; 被设计为私有。 思考并回答:

① 若将其改为公有接口,有何优点或风险?:

  • 优点:外部调用者可以直接查询窗口是否包含指定按钮,增加了接口的灵活性,部分场景下可以减少一次函数调用。
  • 风险:破坏类的封装性,将内部查找的实现细节暴露给外部;若后续内部存储结构从 vector 改为 map 等其他结构,公有接口需要同步修改,降低了代码的可维护性;同时该函数仅为内部辅助工具,对外暴露会让类的接口冗余、职责不清晰。

② 设计类时,如何决策一个成员函数应为 public 还是 private?(可从“用户是否需要”、“是否仅为内部实现细:

  • public:类对外提供的核心功能,是调用者需要直接使用的操作,代表类的对外能力。
  • private:仅为内部实现服务的辅助函数、内部状态,是实现细节;外部不需要了解,且暴露后容易破坏对象内部状态、增加耦合的成员,应设为私有。
    节”、“是否易破坏对象状态”等角度分析。)

问题3: Button 的接口 const std::string& get_label() const; 返回 const std::string& 。对比以下

两种接口设计在性能和安全性方面的差异并精炼陈述。
接口1: const std::string& get_label() const;
接口2: std::string get_label() const;

  • 接口 1(返回 const 引用):性能上避免了字符串的拷贝构造,开销更低;安全性上返回 const 引用,外部无法修改类的私有成员 label_,保证了数据的只读性与内部状态安全。
  • 接口 2(返回值):性能上会生成一份字符串副本,产生拷贝开销;返回的是独立对象,外部修改副本不影响类内部数据,但对于只读场景来说属于不必要的性能损耗。

问题4:标准库探索

① 把window.hpp中所有 xx.push_back(Button(xxx)) 改成 xx.emplace_back(xxx) ,观察程序是否正常
运行;查阅资料,回答两种写法的差别。:程序可以正常运行。

  • push_back:先构造一个临时的 Button 对象,再将其移动 / 拷贝到 vector 的内存中,会产生一次临时对象的构造与析构。
  • emplace_back:直接在 vector 分配的内存上原地构造 Button 对象,省去了临时对象的创建与销毁,效率更高,参数直接传递给元素的构造函数。

② 用标准库改写 window::has_button() 实现,这样编写是否可以?查阅资料,简述 std::any_of() 功能、
参数和返回值意义。:该改写是可行的。

  • std::any_of 功能:判断指定区间内是否存在至少一个满足谓词条件的元素。
  • 参数:首尾迭代器(指定区间)、一个返回 bool 的谓词函数。
  • 返回值:bool 类型,只要有一个元素满足条件就返回 true,全部不满足返回 false。

③ 用标准库改写 window::click_button() 实现,这样编写是否可以?查阅资料,简述 std::find_if() 功
能、参数和返回值意义。:该改写是可行的。

  • std::find_if 功能:在指定区间内查找第一个满足谓词条件的元素。
  • 参数:首尾迭代器(指定区间)、一个返回 bool 的谓词函数。
  • 返回值:指向第一个满足条件元素的迭代器;若未找到,返回区间的尾后迭代器(end ())。

实验任务2

源代码

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

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

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(auto &i: v)
        output2(i);
}

截图

image

问题1:测试模块1中这两行代码分别完成了什么构造? v1 、 v2 各包含多少个值为 42 的数据项?:

  • std::vector<int> v1(5, 42):调用 vector 的带参构造函数,创建一个包含 5 个 int 元素的 vector,每个元素的初始值都为 42。
  • const std::vector<int> v2(v1):调用 vector 的拷贝构造函数,以 v1 为模板创建一个完全相同的新 vector v2。
  • v1 和 v2 都包含 5 个值为 42 的数据项。

问题2:测试模块2中这两行代码执行后, v1.size() 、 v2.size() 、 v1[0].size() 分别是多少?:

  • v1.size() = 2(外层 vector 包含 2 个内层 vector 元素)
  • v2.size() = 2(深拷贝后与 v1 大小一致)
  • v1[0].size() = 3(第一个内层 vector 包含 {1,2,3} 三个元素)

问题3:测试模块1中,把 v1[0] = -1; 写成 v1.at(0) = -1; 能否实现同等效果?两种用法有何区别?:

可以实现同等的赋值效果,两者都能修改第一个元素的值。
区别:

  • [] 运算符:不进行边界检查,下标越界时属于未定义行为,运行速度更快。
  • at() 成员函数:会进行下标边界检查,若越界会抛出 std::out_of_range 异常,安全性更高,有少量的检查开销。

问题4:测试模块2中执行 v1[0].push_back(-1); 后

① 用以下两行代码,能否输出-1?为什么?:可以输出 -1。
原因:r 是 v1 [0] 的 const 引用,它和 v1 [0] 指向同一个 vector 对象。v1 [0] 执行 push_back 后,对象本身的内容发生了改变,const 引用只是限制了 “通过 r 去修改对象”,但对象本身通过其他途径被修改是可见的,因此通过 r 可以读取到新添加的 -1。

② r定义成用 const & 类型接收返回值,在内存使用上有何优势?有何限制?:优势:避免了 vector 对象的拷贝,尤其是当 vector 元素很多时,能节省大量内存和拷贝的时间开销。
限制:不能通过该引用修改 vector 内的元素,只能进行只读访问。

问题5:观察程序运行结果,反向分析、推断:

① 标准库模板类 vector 的复制构造函数实现的是深拷贝还是浅拷贝?:标准库 vector 的拷贝构造函数实现的是深拷贝。修改 v1 的元素后,v2 的数据完全不受影响,说明两者拥有独立的内存空间,数据互不干扰,符合深拷贝的特征。

② vector::at() 接口思考: 当 v 是 vector 时, v.at(0) 返回值类型是什么?当 v 是 const
vector 时, v.at(0) 返回值类型又是什么?据此推断标准库 std::vector 的 at() 接口是否必须提供带const 修饰的重载版本?:非 const 的 vector<int> 调用 at(0),返回值类型为 int&(可修改的左值引用);const 的 vector<int> 调用 at(0),返回值类型为 const int&(只读引用)。
因此 std::vector 的 at() 必须提供 const 重载版本:const 对象只能调用 const 成员函数,若没有 const 重载,const 对象将无法使用 at () 接口,不符合 const 正确性原则。

实验任务3

源代码

vectorlnt.hpp

点击查看代码
#pragma once
#include <iostream>
#include <stdexcept>

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

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

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

问题1:当前代码中, vectorInt 接口 assign() 实现是安全版本。如果把 assign 实现改成版本2,运行程序,提供运行截图,观察test3模块输出结果有无异常。逐条指出版本2存在的安全隐患和缺陷。(提示:对比两个版本,找出差异化代码,加以分析):

版本 2 的 assign 存在严重的安全缺陷,运行 test3 的 x.assign(x) 自赋值时会出现未定义行为(程序崩溃、输出乱码等异常)。
缺陷逐条分析:

  1. 自赋值崩溃:没有自赋值判断。当 vi 就是对象自身时,先执行 delete[] pdata_ 释放了自身内存,后续读取 vi.pdata_[i] 就是访问已释放的野指针,造成内存访问错误。
  2. 异常不安全:如果 new int[n_] 抛出内存不足异常,旧的内存已经被释放,对象会处于无效状态,造成资源泄漏和状态破坏。原安全版本先申请新内存、复制数据,成功后再释放旧内存,保证异常发生时原对象不受影响。

截图

image

问题2:当前验证性代码中, vectorInt 重载接口 at() 内部代码完全相同。若把非 const 版本改成如下实现,可消除重复并遵循“最小化接口”原则(未来如需更新接口,只更新const接口,另一个会同步)。

查阅资料,回答:
① static_cast<const vectorInt*>(this) 的作用是什么?转换前后 this 的类型分别是什么?转换目的?:

  • 作用:将当前对象的 this 指针转换为指向 const 对象的指针。
  • 转换前:this 是 vectorInt* 类型(指向非 const 对象)。
  • 转换后:const vectorInt* 类型。
  • 目的:让非 const 的成员函数能够调用 const 版本的 at(),复用 const 版本的实现逻辑,消除代码重复。

② const_cast<int&> 的作用是什么?转换前后的返回类型分别是什么?转换目的?:

  • 作用:去除引用的 const 属性。
  • 转换前:const int& 类型(const 版本 at () 的返回值)。
  • 转换后:int& 类型。
  • 目的:非 const 版本的 at () 需要返回可修改的左值引用,调用 const 版本得到的是只读引用,通过 const_cast 去掉 const 限定,返回可写引用,同时复用已有实现。

问题3: vectorInt 类封装了 begin() 和 end() 的const/非const接口。

① 以下代码片段,分析编译器如何选择重载版本,并总结这两种重载分别适配什么使用场景。:
编译器根据调用对象的 const 属性选择重载版本:

  • v1.begin():v1 是非 const 对象,调用非 const 版本的 begin(),返回 int*。
  • v2.begin():v2 是 const 对象,调用const 版本的 begin(),返回 const int*。
  • 适用场景:非 const 重载用于需要修改元素的遍历场景;const 重载用于只读遍历,保证数据不被修改,同时支持 const 对象正常使用接口。

问题4:构造函数 vectorInt(int n, int value) 、 vectorInt(const vectorInt &vi) 及接口 assign 包含内存块的赋值或复制操作。使用算法库 改成如下写法是否可以?回答这3行更新代码的功能。:

三处改写都是可行的。

  • 更新 1 std::fill_n(pdata_, n_, value):从 pdata_ 起始的连续 n_ 个内存位置,全部赋值为 value,替代手写循环初始化。
  • 更新 2 std::copy_n(vi.pdata_, vi.n_, pdata_):将 vi 中连续 n_ 个元素复制到当前对象的内存中,替代手写循环拷贝,用于拷贝构造函数。
  • 更新 3 std::copy_n(vi.pdata_, vi.n_, ptr):将 vi 的数据复制到新申请的 ptr 内存中,替代 assign 中的手写循环拷贝。
    使用标准库算法代码更简洁、可读性更强,且标准库实现通常有底层优化,执行效率不低于手写循环。

实验任务4

源代码

matrix.h

点击查看代码
#pragma once
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 <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];
}

// 非const版本at,复用const实现
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 << pdata_[i * n_cols_];
        for (int j = 1; j < n_cols_; ++j) {
            std::cout << ", " << pdata_[i * n_cols_ + 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';
}

截图

image

问题解答

set 接口的潜在风险
存在明显的安全风险:当传入的数组实际长度小于 size 时(例如数组只有 5 个元素,却传入 size=10),std::copy_n 会继续向后读取越界内存,造成未定义行为,可能读取到垃圾数据甚至程序崩溃。
接口仅校验了 size 是否等于矩阵元素总数,但无法校验裸指针指向的内存是否真的有 size 个元素,调用者传参失误时会触发越界访问。

优化方案

  1. 替换裸指针参数,改用 std::vector<double> 等标准容器作为参数,容器自带大小信息,可在编译期保证数据长度匹配,从根源避免越界。
  2. 若必须保留裸指针接口,可在文档中明确约束调用者必须保证内存长度合法,并增加调试期的断言辅助排查。

实验任务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();
}

// 补足1:查找联系人索引
int ContactBook::index(const std::string& name) const {
    for (size_t i = 0; i < contacts_.size(); ++i) {
        if (contacts_[i].get_name() == name) {
            return static_cast<int>(i);
        }
    }
    return -1;
}

// 补足2:按姓名字典序升序排序
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();
    return 0;
}

截图

image

posted @ 2026-11-26 23:05  Wimous  阅读(6)  评论(0)    收藏  举报