实验三:类和对象

实验任务一:

源码:

#include <iostream>
#include <string>

class Button {
public:
    Button(const std::string &label_);
    const std::string& get_label() const; //‘&’不是函数的引用,而是一个“返回值为const std::string&的成员函数”
    void click();

private:
    std::string label;
};

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";
}
button.hpp
#pragma once

#include <iostream>
#include <vector>
#include <algorithm>
#include "button.hpp"

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;

private:
    std::string title;
    std::vector<Button> buttons;
};

window::window(const std::string &title_):title{title_}{
    buttons.push_back(Button("close")); //<vector>中push_back:向vector容器末尾添加一个标签为"close"的Button对象
}

inline void window::display() const {
    std::string s(40,'*');
    std::cout << s << std::endl;
    std::cout << s << std::endl;
    std::cout << "window: " << title << std::endl;
    int cnt = 0;
    for(const auto &button: buttons) //for(元素声明:可遍历对象)//&引用,直接操作容器里的原始元素,减少内存浪费
        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;
}
window.hpp
#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();
}
task1.cpp

运行结果测试截图:

1

回答问题:

  • 问题1:这个范例中, Window 和 Button 是组合关系吗? 

答:Window和Button是组合关系

  • 问题2:bool has_button(const std::string &label) const; 被设计为私有。

     思考并回答:(1)若将其改为公有接口,有何优点或风险?

           (2)设计类时,如何判断一个成员函数应为 public 还是 private?(可从“用户是否需要”、“是否仅为内部实现细节”、“是否易破坏对象状态”等角度分析。) 

答:(1)若将其改为公有接口,优点:用户可以查看窗口是否有指定标签的按钮;缺点:把类的内部暴露给了外部,如果有外部调用者基于这个接口做了一些操作,只要这个接口内部发生修改,就可能影响所有基于这个接口的外部代码。

  (2)①用户是否需要:如果成员函数是用户必须要使用的接口,应为public

      ②是否仅为内部实现细节:如果成员函数只是实现类内部的细节部分设为private即可。

      ③是否易破坏对象状态:如果用户在使用成员函数时可能会修改成员函数(破坏对象状态)导致类内部逻辑错误则应设为private

  • 问题3:Button 的接口 const std::string& get_label() const; 返回 const std::string& 。简要说明以下两种接口设计在性能和安全性方面的差异。

          接口1: const std::string& get_label() const; 接口2: const std::string get_label() const; 

答:两种接口差别主要是接口1中有'&',表示返回的值是引用类型(返回引用),可以直接传递参数不会创建副本,减少内存占据,结合get_label在后续定义中加了inline内联函数定义,可以进一步判断接口1是想提高代码的简洁性和高效性,性能更强。安全性方面,我仍然觉得接口1的安全性更强,因为加了const,所以接口1返回的是const引用,不会修改原对象;而接口2返回拷贝,会生成返回值的副本,额外增加了开销,性能较弱。同时接口2也有const保护,没有安全性的优势,同时拷贝本身可能引入额外的风险。

  • 问题4:把代码中所有 xx.push_back(Button(xxx)) 改成 xx.emplace_back(xxx) ,观察程序是否正常运行;查阅资料,回答两种写法的差别。 

答:修改了25行和56行处push_back,程序正常运行。查阅资料后,push_back会先对对象进行拷贝操作,然后把副本加入vector中,而emplace_back直接把参数传入构造函数中。核心区别是push_back接收已经构造好的对象,而emplace_back原地构造。所以在这里我认为可以修改一下代码,不需要创建Button类的对象再调用函数,可以直接写成buttons.emplace_back("close");

image

实验任务二:

源码:

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

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: "; output3(v1);
    std::cout << "v2: "; output3(v2);

    v1.at(0).push_back(-1);
    std::cout << "*********修改v1[0]后**********\n";
    std::cout << "v1: \n"; output3(v1);
    std::cout << "v2: \n"; output3(v2);
}

//使用xx.at()+循环输出vector<int>数据项
void output1(const std::vector<int> &v)
{
    if(v.size() == 0)
    {
        std::cout << '\n';
        return;
    }

    std::cout << v.at(0);
    for(auto i = 1;i < v.size();++i)
        std::cout << ", " <<v.at(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);
}
task2.cpp

运行结果测试截图:

image

回答问题:

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

image

答:第一行调用vector中填充构造函数完成了成员为int型的vector v1的构造,vector中包含5个元素,每个元素的值都为42。第二行通过调用vector中拷贝构造函数复制v1中所有元素完成v2的构造,并且加了const保护,不可修改v2中的值,以完成后续深复制验证;v1和v2都包含5个值为42的数据项。

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

image

 答:v1.size() = 2, v2.size() = v1.size() = 2, v1[0].size() = 3。vector<int>嵌套使用时,对于外层vector, .size()表示其内部vector个数,对于内层vector, [i].size()表示其内部第i个vector包含的int元素个数

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

答:能实现同等效果。通过查阅资料,我了解到.at()是容器类的一个成员函数,可以根据索引或键从容器中获取对象。但是.at()和直接用[i]下标索引的核心区别是.at()有边界检查功能,如果超出检索范围,它会提示std::out_of_range而不是报错,可以有效地提示错误。

image

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

       (1)用以下两行代码,能否输出-1?为什么? 

image

答:可以输出-1,因为在嵌套vector使用时,v1.at(0)访问的是嵌套vector中第一个内部子vector,而r是这个子vector的引用,因为上面执行了push_back,所以子vector的size变为了4,通过r.at(4-1)访问就能输出-1。

image

       (2)r定义成用 const & 类型接收返回值,在内存使用上有何优势?有何限制?

答:r加上const修饰变为const &是常量引用,起到了通过该引用不能修改对象的作用,可以避免不必要的拷贝,但同时也限制了这个子vector后续无法修改元素。

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

       (1)标准库模板类 vector 的复制构造函数实现的是深复制还是浅复制?

答:深复制。对v1的修改不会影响v2。

       (2)vector::at() 接口思考:当 v 是 vector 时,v.at(0) 返回值类型是什么?当 v 是 const vector 时,v.at(0) 返回值类型又是什么?据此推断 .at() 是否必须提供带 const 修饰的重载版本?

答:当 v 是 vector 时,v.at(0) 返回值类型是对应元素的&引用,通过它可以直接修改元素;当 v 是 const vector 时,v.at(0) 返回值类型是const &常量引用,不允许通过它修改元素;据此推断.at()必须提供带const类型的重载版本,因为当操作const类型的vector时需要调用const的at()接口以确保类型匹配,保证安全访问。

实验任务三:

源码:

#pragma once

#include <iostream>

// 动态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 *ptr;  // 数据区
};

vectorInt::vectorInt():n{0}, ptr{nullptr} {
}

vectorInt::vectorInt(int n_): n{n_}, ptr{new int[n]} {
}

vectorInt::vectorInt(int n_, int value): n{n_}, ptr{new int[n_]} {
    for(auto i = 0; i < n; ++i)
        ptr[i] = value;
}

vectorInt::vectorInt(const vectorInt &vi): n{vi.n}, ptr{new int[n]} {
    for(auto i = 0; i < n; ++i)
        ptr[i] = vi.ptr[i];
}

vectorInt::~vectorInt() {
    delete [] ptr;
}

int vectorInt::size() const {
    return n;
}

const int& vectorInt::at(int index) const {
    if(index < 0 || index >= n) {
        std::cerr << "IndexError: index out of range\n";
        std::exit(1);
    }

    return ptr[index];
}

int& vectorInt::at(int index) {
    if(index < 0 || index >= n) {
        std::cerr << "IndexError: index out of range\n";
        std::exit(1);
    }

    return ptr[index];
}

vectorInt& vectorInt::assign(const vectorInt &vi) { 
    if(this == &vi) 
        return *this;

    int *ptr_tmp;
    ptr_tmp = new int[vi.n];
    for(int i = 0; i < vi.n; ++i)
        ptr_tmp[i] = vi.ptr[i];
    
    delete[] ptr;
    n = vi.n;
    ptr = ptr_tmp;
    return *this;
}

int* vectorInt::begin() {
    return ptr;
}

int* vectorInt::end() {
    return ptr+n;
}

const int* vectorInt::begin() const {
    return ptr;
}

const int* vectorInt::end() const {
    return ptr+n;
}
vectorInt.hpp
#include "vectorInt.hpp"
#include <iostream>

void test1();
void test2();
void output1(const vectorInt &vi);
void output2(const vectorInt &vi);

int main() {
    std::cout << "测试1: \n";
    test1();

    std::cout << "\n测试2: \n";
    test2();
}

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

// 使用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';
}
task3.cpp

运行结果测试截图:

image

回答问题:

  • 问题1:当前验证性代码中, vectorInt 接口 assign 实现是安全版本。如果把 assign 实现改成版本2, 逐条指出版本2存在的安全隐患和缺陷。(提示:对比两个版本,找出差异化代码,加以分析)
//版本1
vectorInt& vectorInt::assign(const vectorInt &vi) { 
    if(this == &vi) 
        return *this;
    int *ptr_tmp;
    ptr_tmp = new int[vi.n];
    for(int i = 0; i < vi.n; ++i)
        ptr_tmp[i] = vi.ptr[i];
    delete[] ptr;
    n = vi.n;
    ptr = ptr_tmp;
    return *this;
}
// 版本2
vectorInt& vectorInt::assign(const vectorInt &vi) { 
 delete[] ptr;
 n = vi.n;
 ptr = new int[n];
 for(int i = 0; i < n; ++i)
     ptr[i] = vi.ptr[i];
 return *this;
}

答:两个版本主要有两个核心差异,第一个是安全版本if(this == &vi) return *this;这个操作可以防止自赋值,如a.assign(a)所导致的内存错误问题;第二个差异是安全版本先进行赋值再修改指针指向的内存,而版本2先释放了原先指针内存然后再赋值,这样会导致逻辑错误内存分配不明确,不能清晰的判断是否是深复制

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

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

答:static_cast(tihs)把this指针的非const类型变为<const vectoInt>中的const类型,让非const对象能直接调用const at函数。

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

答:const_cast(this)把转换成const类型的this再恢复到非const的int &类型,以完成后续调用at函数时修改对应索引的值。

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

  (1)以下代码片段,分析编译器如何选择重载版本,并总结这两种重载分别适配什么使用场景。

vectorInt v1(5);
const vectorInt v2(5);
auto it1 = v1.begin();    // 调用哪个版本?
auto it2 = v2.begin();    // 调用哪个版本?

答:v1调用非const版本,v2调用const版本。v1适合想要对vectorInt内部做修改时使用,v2适合仅查找不做修改时使用。

  (2)拓展思考(选答*):标准库迭代器本质上是指针的封装。 vectorInt 直接返回原始指针作为迭代器,这种设计让你对迭代器有什么新的理解? 

答:据我对标准库迭代器的了解,标准库迭代器适用于所有容器,本质上提供一种统一的元素访问方式,比如list,vector,array。其中像list链表它的内存是不连续的,通过迭代器仍然能够按序找到对应元素,但是我们自己封装的vectorInt本质上还是分配一片连续内存的数组,返回原始指针作为迭代器,因此像list这种存储结构是没法实现的。所以我觉得标准库迭代器是一种更加安全通用的原始指针的封装,可以完成一些原始指针物理上做不到的事情。

  • 问题4:以下两个构造函数及 assign 接口实现,都包含内存块的赋值/复制操作。使用算法库改写是否可以?回答这3行更新代码的功能。 
vectorInt::vectorInt(int n_, int value): n{n_}, ptr{new int[n_]} {
 std::fill_n(ptr, n, value);   // 更新
}
vectorInt::vectorInt(const vectorInt &vi): n{vi.n}, ptr{new int[n]} {
 std::copy_n(vi.ptr, vi.n, ptr); // 更新
}
vectorInt& vectorInt::assign(const vectorInt &vi) { 
 if(this == &vi) 
     return *this;   
 int *ptr_tmp;
 ptr_tmp = new int[vi.n];
 std::copy_n(vi.ptr, vi.n, ptr_tmp); // 更新
 delete[] ptr;      
 n = vi.n;
 ptr = ptr_tmp;
 return *this;
}

答:这三行更新的代码结构可以抽象成fill(i,j,n),copy(i,n,ptr),fill想实现的是从i到j用n填满,从而实现内存块的赋值操作;copy想做的是从i中复制n个元素到ptr指向的内存区域,从而实现内存块的复制操作。可以使用算法库改写,这样算法函数封装了内存赋值/复制操作的逻辑,让代码更加简洁可读

实验任务四:

源码:

#include <iostream>
#include <cstdlib>
#include "matrix.hpp"

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

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, 3, -1);
    const Matrix m2(m1);
    
    std::cout << "矩阵对象m1: \n";   m1.print();
    std::cout << "矩阵对象m2: \n";   m2.print();

    m1.clear();
    m1.at(0, 0) = 1;

    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()) {
        std::cerr << "IndexError: row index out of range\n";
        exit(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';
}
task4.cpp
#pragma once

#include <iostream>
#include <algorithm>
#include <cstdlib>

// 类Matrix声明
class Matrix {
public:
    Matrix(int rows_, int cols_, double value = 0); // 构造rows_*cols_矩阵对象, 初值value
    Matrix(int rows_, double value = 0);    // 构造rows_*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 *ptr;    // 数据区
};
matrix.hpp
#include "matrix.hpp"

Matrix::Matrix(int rows_, int cols_, double value):n_rows{rows_},n_cols{cols_}{
    if(n_rows < 0 || n_cols < 0)
    {
        std::cout << "行数/列数不能为负数!\n" << std::endl;
        ptr = nullptr;
        return;
    }
    ptr = new double[n_rows *n_cols];
    for(int i = 0;i < n_rows*n_cols;i++)
        ptr[i] = value;
}

Matrix::Matrix(int rows_, double value):n_rows{rows_},n_cols{rows_}{
    if(n_rows < 0 || n_cols < 0)
    {
        std::cout << "行数/列数不能为负数!\n" << std::endl;
        ptr = nullptr;
        return;
    }
    ptr = new double[n_rows *n_cols];
    for(int i = 0;i < n_rows*n_rows;i++)
        ptr[i] = value;
}

Matrix::Matrix(const Matrix &x):n_rows{x.n_rows},n_cols{x.n_cols}{
    if(n_rows < 0 || n_cols < 0)
    {
        std::cout << "行数/列数不能为负数!\n" << std::endl;
        ptr = nullptr;
        return;
    }
    ptr = new double[n_rows *n_cols];
    for(int i = 0;i < n_rows*n_cols;i++)
        ptr[i] = x.ptr[i];
}

Matrix::~Matrix(){
    delete []ptr;
}

// 按行复制pvalue指向的数据,要求size=rows*cols,否则报错退出
void Matrix::set(const double *pvalue, int size){
    if(size != n_rows*n_cols)
        std::cout << "out of size!\n" << std::endl;
    std::copy(pvalue,pvalue + size,ptr);
}

// 矩阵对象数据项置0
void Matrix::clear(){
    std::fill(ptr,ptr + n_rows*n_cols,0.0);
}

// 返回矩阵对象索引(i,j)对应的数据项const引用(越界则报错后退出)
const double& Matrix::at(int i, int j) const{
    if(i > n_rows || j > n_cols)
    {
        std::cout << "out of range!\n" << std::endl;
        exit(EXIT_FAILURE);
    }
    return ptr[i * n_cols + j];
}

// 返回矩阵对象索引(i,j)对应的数据项引用(越界则报错后退出)
double& Matrix::at(int i,int j){
    if(i > n_rows || j > n_cols)
    {
        std::cout << "out of range!\n" << std::endl;
        exit(EXIT_FAILURE);
    }
    return ptr[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++)
    {
        std::cout << ptr[i * n_cols];
        for(int j = 1;j < n_cols;j++)
        {
            std::cout << ", " << ptr[i * n_cols + j];
        }
        std::cout << "\n";
    }
}
matrix.cpp

运行结果测试截图:

image

实验任务五:

源码:

#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;   // 必填项
};

Contact::Contact(const std::string &name_, const std::string &phone_):name{name_}, phone{phone_} {
}

const std::string& Contact::get_name() const {
    return name;
}

const std::string& Contact::get_phone() const {
    return phone;
}

void Contact::display() const {
    std::cout << name << ", " << phone;
}
contact.hpp
# pragma  once

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include "contact.hpp"

// 通讯录类
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;  // 返回联系人在contacts内索引,如不存在,返回-1
    void sort(); // 按姓名字典序升序排序通讯录

private:
    std::vector<Contact> contacts;
};

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

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

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

void ContactBook::display() const {
    for(auto &c: contacts) {
        c.display(); 
        std::cout << '\n';
    }
}

size_t ContactBook::size() const {
    return contacts.size();
}

// 待补足1:int index(const std::string &name) const;实现
// 返回联系人在contacts内索引; 如不存在,返回-1
int ContactBook::index(const std::string &name) const{
    for(int i = 0;i < contacts.size();i++)
    {
        std::string get_name = contacts[i].get_name();
        if(name == get_name)
        return i;
    }
    return -1;
}

// 待补足2:void ContactBook::sort();实现
// 按姓名字典序升序排序通讯录
void ContactBook::sort(){
    //使用sort,内部使用lambda表达式对contact类自定义比较
    //lambda表达式:[capture](parameters) -> return_type{//函数体(执行逻辑}
    std::sort(contacts.begin(),contacts.end(),[](const Contact&a,const Contact&b){return a.get_name() < b.get_name();});
}
contactBook.hpp
#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");
}

int main() {
    test();
}
task5.cpp

运行结果测试截图:

image

posted @ 2025-11-23 15:55  黎明Z  阅读(18)  评论(0)    收藏  举报