实验三

实验3

任务一

源代码

点击查看代码

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

运行截图

屏幕截图 2026-11-26 130042

问题

  1. 是组合关系。Window 对象创建时,vector 里的按钮对象跟着一起创建;Window 析构时 vector 析构,里面的 Button 也一起析构,不需要自己 new 和 delete,生命周期完全由 Window 管,属于 has-a 关系。

  2. ① 改成公有的话,外部可以直接判断“有没有这个按钮”,写别的方法时方便一些。风险是这个函数原本只是 add_button 和 click_button 的内部实现,公开以后外部代码会依赖它,以后如果换一种存储方式(比如改成 map),用到它的地方都得跟着改;另外接口开得越多,越容易在别处误用,把内部状态搞乱。

② 我一般这样判断:外部确实需要、调用又不会破坏对象状态的功能放 public,比如 add_button、display、close;纯粹给本类内部用的辅助函数放 private,比如 has_button;会改动内部数据、容易用错的也放 private,再用一个安全点的上层接口包一层,比如通讯录里的 sort() 就没有对外公开。

  1. 接口1 返回 const 引用,直接给出对象内部那个字符串,不复制,字符串比较大或者调用很频繁时能省下一次构造和拷贝,外面也拿不到可修改的引用,不会改坏对象。接口2 返回值,每次调用都要复制一份 string,有额外开销,好处是外面拿到的是独立副本,怎么改都不影响对象本身。这里的 label_ 是 string 类型,用接口1 更合适;只有确实需要给出去一份独立数据时才用返回值的写法。

  2. ① 改成 emplace_back 后程序能正常运行,输出和原来一样。区别在于 push_back(Button(xxx)) 是先在外部构造一个临时 Button 对象,再把它移动或者复制进 vector;emplace_back(xxx) 是把参数直接传到 vector 尾部的内存上构造对象,少了一次临时对象的构造和析构。

② 可以,改完输出一样。std::any_of 是在前两个迭代器给出的区间里检查有没有元素满足第三个参数的判断条件,只要有一个满足就返回 true,全都不满足返回 false。原来的 has_button 做的就是这件事,所以可以直接替换。

③ 也可以。std::find_if 同样是三个参数,返回区间里第一个满足条件的元素的迭代器,一个都没有就返回 end()。拿到迭代器后判断是不是 end(),不是就调用 click(),是就输出 no button,和原来的循环效果一样。

任务二

源代码

点击查看代码

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

运行截图

屏幕截图 2026-11-26 130239

问题

  1. v1(5, 42) 是“指定大小加初值”的构造,一共 5 个 42;v2(v1) 是拷贝构造,把 v1 的数据复制一份,也是 5 个 42。所以 v1、v2 各包含 5 个值为 42 的数据项。

  2. v1.size() 是 2,v2.size() 是 2,v1[0].size() 是 3。

  3. 可以,v1.at(0) = -1 效果和 v1[0] = -1 一样。区别是 [] 不做越界检查,下标越界属于未定义行为,可能读到别的数据甚至崩掉;at() 会检查下标,越界时抛 std::out_of_range 异常,安全一些,代价是多一次判断。调试阶段用 at() 更容易发现问题。

  4. ① 能不能输出 -1 要看这两行取的是哪个对象。如果取的是 v1[0],能输出 -1,因为 push_back 确实已经改动了 v1[0];如果取的是 v2[0],就输出不了,v2 是 v1 的深拷贝,v1 后面怎么改,v2 里还是 1, 2, 3。

② r 用 const & 接收,等于直接引用 v1[0] 里的那个 vector,不复制数据,省内存也省时间,元素多的时候差别比较明显。限制是 r 带 const,不能通过 r 修改里面的元素;而且它绑在 v1[0] 上,如果 v1 被销毁,或者因为扩容导致内部数据搬了位置,r 就成了悬空引用。

  1. ① 是深拷贝。修改 v1[0] 之后 v2 没有任何变化,说明两个对象各自有一块独立的内存,不是共用同一块。

② 当 v 是 vector 时,v.at(0) 返回 int&;当 v 是 const vector 时,返回 const int&。如果不提供 const 版本,用 const 对象调用 at() 会编译不通过,因为 const 对象的 this 是 const 指针,只能调用 const 成员函数,所以必须提供 const 重载。

任务三

源代码

点击查看代码

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

运行截图

屏幕截图 2026-11-26 130637

屏幕截图 2026-11-26 130728

问题

  1. 换成版本2 之后,测试1、测试2 输出正常,测试3(x.assign(x))出问题了:x 打印出来变成 -1790284576, 464, -1790312112, 464, 42 这样的值,每次运行数字都不一样,有时还会直接崩掉。版本2 的问题有这几个:

(1)少了自赋值判断。x.assign(x) 时形参 vi 就是对象自己,版本2 里没有 if(this == &vi) return *this; 这一步。

(2)先 delete 再复制,是释放后使用。delete[] pdata_ 之后这块内存已经还给系统,接着又用 vi.pdata_[i] 去读它,而 vi 就是自己,指针还是同一个,读到的已经是失效的数据,所以打印出来是垃圾值。原版本先把数据复制到新申请的 ptr,最后才 delete 旧内存,自赋值也不会读到已释放的内存。

(3)异常不安全。版本2 是先 delete 再 new,如果 new 抛异常(比如内存不够),对象就停在 pdata_ 已释放、n_ 已改掉的状态,后面再访问就是野指针。原版本在 new 成功之前不动对象,出异常时对象还是好的。

(4)版本2 把 n_ 和 pdata_ 的赋值顺序换了,中间出错,对象内部就自相矛盾(n_ 是新值,pdata_ 还是旧指针),这也是原版本用临时指针 ptr 过渡的原因。

  1. ①目的是让后面调用的 at() 匹配到 const 版本,这样非 const 版本就不用把越界检查和取值再写一遍。

② const 版本的 at() 返回的是 const 引用,而非 const 版本要返回一个能修改的引用,所以要把 const 去掉。这里敢这么写,是因为调用它的对象本身不是 const 的,只是借 const 接口做了一次检查。

  1. v1 是非 const 对象,调用非 const 版本的 begin(),it1 是 int;v2 是 const 对象,只能调用 const 版本,it2 是 const int。非 const 版本适合需要修改元素的场合,比如循环里给元素赋值;const 版本适合只读遍历的场合,比如 output2 这种输出函数,形参是 const 引用时也只拿得到 const 迭代器。

  2. 可以,三行都是标准库算法,编译运行都没问题,结果和原来一致。用算法库代替手写循环,代码更短,下标也少写错。

任务四

源代码

点击查看代码

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_]} {
    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)对应的数据项引用
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) {
            if(j > 0)
                std::cout << ", ";
            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';
}

运行截图

屏幕截图 2026-11-26 130827

问题

接口 set(const double pvalue, int size) 和测试模块一起看,是有风险的。它只检查 size 和 rowscols 是否相等,不检查 pvalue 指向的数组到底有多长。把测试模块里的数组改成 double x[5] = {1, 2, 3, 4, 5}; 再用输入 2 5 运行,size 传进来是 10,正好等于 n_rows_*n_cols_,检查通过,但 x 只有 5 个元素,copy_n 会往后多读 5 个 double,属于越界读。程序不会报错,打印出来是 6.9516e-310 这种垃圾值。

优化的话,可以让接口自己知道数据长度,比如改成 set(const std::vector &values),用 values.size() 和 rows*cols 比较,边界交给 vector 保证;或者用模板接收数组,编译期拿到长度做静态检查。如果不能改接口,至少要在文档里写清楚调用者必须保证数组长度,或者干脆不用 set(),改成 set(i, j, value) 逐个赋值,让越界检查发生在 at() 里。

任务五

源代码

点击查看代码

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 index(const std::string &name) const;实现
// 返回联系人在contacts内索引; 如不存在,返回-1
inline 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();实现
// 按姓名字典序升序排序通讯录
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();
}

运行截图

屏幕截图 2026-11-26 130911

问题

index():用一个循环遍历 contacts_,把每个联系人的 get_name() 和形参 name 比较。std::string 的 == 是逐字符比较,区分大小写,正好符合题目要求。找到就返回下标,循环结束还没找到就返回 -1。返回值类型是 int,所以用下标访问时注意转换一下。

sort():调用 std::sort,第三个参数传一个 lambda,比较两个联系人的 get_name(),返回前者是否小于后者,这样就是按姓名字典序升序排列。add() 里每次添加成功都会调用一次 sort(),所以 contacts_ 一直是排好序的,find() 和 display() 的输出顺序也就固定了。用 lambda 是因为比较的是私有的排序规则,写在类里比较清楚,也不必额外定义比较函数。

拓展思考:这个通讯录还比较简陋。可以接着加修改联系人的功能(先用 index() 找到位置,再改电话),加手机号格式校验,加异常处理,把数据存到文件里做持久化;再往后可以做分组和模糊查找。扩展时尽量不动现有的公有接口,新功能用新方法加,这样测试代码和原来的调用方都不用改。

总结

这次实验主要练组合、深拷贝和标准库的使用。任务一让我第一次把两个类真正组合起来用,看清楚对象的创建和析构是跟着外层对象走的,不用手动管理;也理解了为什么有些函数要放 private,接口开得太多后面维护很麻烦。
任务二和任务三是同一个知识点从两个角度看。用标准库 vector 时,深拷贝是它自动做好的,改一个不影响另一个;自己写 vectorInt 才看清深拷贝到底做了什么:重新申请内存,再逐项复制。assign 的两个版本差别很小,但版本2 在自赋值时会读到已经释放的内存,输出直接变成垃圾值
任务四、任务五是综合练习。matrix 让我注意到接口设计的问题:set() 只用 size 参数做检查,调用者给的数组太短时照样能通过,程序不报错但结果是错的,这种错误最难查。通讯录那个任务代码量不大,但补的两个工具函数要和已有代码配合好,比如 sort() 要在 add() 之后调用,index() 返回 -1 的约定要和 remove()、find() 对上。
还有一点体会是标准库用得越多,手写的代码越少,出错的机会也越少。

posted @ 2026-11-26 13:12  qymqym  阅读(9)  评论(0)    收藏  举报