实验3

1. 实验任务1

分别给出button.hpp, window.hpp, task1.cpp源码

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

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

  

及运行测试截图

image

 

回答问题

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

 

是组合(has‑a)关系。

std::vector<Button> buttons_存储的是Button 对象的值,不是指针;vector 内部直接保存 Button 实例。

Window 对象生命周期控制内部 Button 对象:Window 创建时,vector 内 Button 随之构造;Window 销毁,vector 销毁,内部所有 Button 自动析构。Button 完全属于 Window,不能脱离 Window 独立存在,符合组合的 “整体拥有部分,部分生命周期随整体” 的 has‑a 语义。

 

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

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

 

优点:外部代码可以直接调用判断按钮是否存在,外部不用重复写查找逻辑。

风险:该函数是内部实现细节,对外暴露后,类内部后续修改容器(vector 改 map),外部调用代码全部失效;破坏封装,使用者可以过度依赖内部实现。

 

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

 

public:类对外提供的服务,外部用户必须要调用的功能。

private:仅类内部使用,属于实现细节;对外暴露不会给用户带来必要价值,还可能被误用、破坏对象内部状态,则放到 private。

 

问题3:Button的接口const std::string& get_label() const;返回const std::string&。对 比以下两种接口设计在性能和安全性方面的差异并精炼陈述。

 

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

性能:不拷贝字符串,直接返回内部成员的引用,开销小。

安全性:返回 const 引用,外部不能修改内部 label_;但要注意:对象销毁后该引用会悬空。

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

性能:返回会触发string 拷贝构造,产生内存复制,开销更大。

安全性:返回副本,和内部成员完全隔离,不存在悬空引用风险;外部修改副本不会影响对象内部状态。

总结:接口 1 性能更好,但要注意对象生命周期;接口 2 安全隔离,但有拷贝开销。本实验使用 const 引用,因为 Button 对象生命周期比返回的引用更长,安全。

 

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

 

修改为emplace_back("xxx")程序正常运行。

push_back(Button("xxx")):先在外部临时构造Button临时对象,再把这个临时对象移动 / 拷贝存入 vector。

emplace_back("xxx"):直接在 vector 容器内存空间就地构造 Button 对象,不需要产生临时对象,减少拷贝 / 移动,效率更高。

 

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

 

代码可行

std::any_of(first, last, pred)

 参数:first,last迭代器区间;pred谓词(返回 bool 的可调用对象)。

功能:遍历 [first,last)区间,只要任意一个元素满足谓词 pred 返回 true,any_of 就返回 true;全部不满足返回 false。本案例:只要任意一个 button 的 label 匹配,就返回 true。

 

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

 

std::find_if(first, last, pred)

参数:迭代器区间[first,last),谓词 pred。

功能:查找区间中第一个满足谓词 pred 的元素。

返回值:找到返回该元素迭代器;找不到返回last尾后迭代器。代码拿到迭代器,如果不等于 end 就调用 click,否则输出没有该按钮。

 

2. 实验任务2

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

  

及运行测试截图

image

 

回答问题

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

 

v1(5,42):参数化构造函数;创建 5 个元素全部初始化为 42。v1 有5 个 42。

v2(v1):拷贝构造函数,用 v1 复制构造 v2;v2 有5 个 42。

 

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

 

v1.size() = 2(外层两个子 vector)

v2.size() =2(拷贝构造,复制外层)

v1[0].size() =3(第一个子 vector {1,2,3})

 

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

 

能赋值同等效果。

区别:

operator[]下标运算符:不做越界检查,下标越界直接未定义行为(崩溃 / 乱码)。

.at(index):做边界检查;下标越界抛出std::out_of_range异常。

 

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

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

 

可以输出 - 1。

v1[0]返回第一个子 vector 的引用;r绑定到它;v1[0].push_back(-1)修改该子 vector,r 是引用,绑定同一个对象,访问可以读到新增的 - 1。

 

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

 

内存优势:不会拷贝整个 vector,只是引用绑定原对象,几乎零内存开销。

限制:const &绑定后,不能通过 r 修改容器里面的元素;只能读取。

 

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

① 标准库模板类 vector 的复制构造函数实现的是深拷贝还是浅拷贝?

 

vector 拷贝构造实现的是深拷贝:复制之后新旧对象拥有完全独立的数据缓冲区;修改其中一个对象数据,另一个不受影响。

 

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

 

非 const 对象vector<int> v; v.at(0)返回 int&(可修改左值引用)。

const 对象const vector<int> cv; cv.at(0)返回 const int&(只读引用)。

必须提供 const 重载版本:const 对象只能调用 const 成员函数;如果没有 const 版本 at (),const vector 对象无法调用 at () 访问元素。

 

3. 实验任务3

此部分书写内容: 分别给出vectorInt.hpp, task3.cpp源码

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

  

及运行测试截图 (运行时,需输入数值给n。为方便截图,输入取[5, 10]数值)

image

 

回答问题

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

inline vectorInt& vectorInt::assign(const vectorInt &vi) {
    delete[] pdata_;
    n_ = vi.n_;
    pdata_ = new int[n_];
    for(auto i = 0; i < n_; ++i)
        pdata_[i] = vi.pdata_[i];
    return *this;
}

test3 调用x.assign(x);即自己赋值给自己。

隐患:
 缺少自赋值判断 if(this == &vi):自赋值时,第一句delete[] pdata_直接释放本对象的内存;后续读取vi.pdata_[i],vi 就是 * this,已经释放,访问已经释放的内存,未定义行为(程序崩溃、乱码输出)。

内存分配失败风险:先 delete 释放旧内存,再 new 新内存;如果 new 抛出异常,对象 pdata_已经被 delete 置为野指针,对象处于损坏状态,资源泄漏,异常不安全。

 

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

① static_cast(this)的作用是什么?转换前后this的类型分别是什么?转换 目的?

 

static_cast<const vectorInt*>(this)

转换前this:vectorInt*(非 const 对象指针)

转换后:const vectorInt *

作用:给 this 指针加上 const 限定,目的调用 const 版本 at () 函数,服用越界检查逻辑。 

 

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

 

const_cast<int&>(...)

转换前返回值:const int &(const‑at 返回只读引用)

转换后返回值:int &(可修改的引用)

目的:去掉 const 修饰;前提:原始对象本身是非 const 对象,该转换合法安全。

 

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

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

 

非 const 对象 (v1) 优先调用非 const 成员函数,拿到普通指针,可以读写元素。

const 对象 (v2) 只能调用 const 成员函数,拿到 const 指针,只能读,禁止写元素。

 

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

 

修改全部可以正常编译运行。

更新 1:std::fill_n(pdata_, n_, value);:从 pdata_起始位置,写 n_个 value 值,代替 for 循环赋值。

更新 2:std::copy_n(vi.pdata_, vi.n_, pdata_);:从 vi.pdata_复制 vi.n_个元素,拷贝到 pdata_目标内存,代替拷贝构造内部 for 循环复制。

更新 3:std::copy_n(vi.pdata_, vi.n_, ptr);:assign 内部,复制 vi 的 n 个元素到新分配 ptr 缓冲区,替代手动 for 循环复制。

 

4. 实验任务4 分别给出程序matrix.h,matrix.cpp, task4.cpp源码

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 <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版本,复用const at
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 << 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.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';
}

  

及运行测试截图(截图时,换一组输入,如2 5)

image

 

 

回答问题 接口void set(const double *pvalue, int size);的设计与测试模块,是否暴露出潜在风险?(提 示:当测试模块中数组x做如下改动,仍然测试截图运行输入2 3或2 5,结果会暴露什么问题) 如何优化set()接口,确保该接口使用时更安全、可靠

 

如果传入数组实际空间小于size参数值,例如double x[5],但调用 set 传入 size=10;set 函数本身无法知道传入原始数组的真实长度,只依靠参数 size;会造成越界读内存,未定义行为。指针本身不携带数组长度信息。 

优化方案:

C++17 可以用std::span<double>接收数组,携带长度信息;

或者模板函数,接收数组引用,编译期推导出数组真实大小;

或者接收std::vector<double>作为参数,vector 自带 size,杜绝越界读取外部裸指针内存。

 

5. 实验任务5 分别给出程序contact.hpp, contactbook.hpp(补足后版本), task5.cpp源码

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;
    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 index查找索引,找不到返回-1====
inline int ContactBook::index(const std::string &name) const
{
    for(int i = 0; i < contacts_.size(); ++i)
    {
        if(contacts_[i].get_name() == name)
        {
            return i;
        }
    }
    return -1;
}

//=====补全2 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();
    return 0;
}

  

及运行测试截图

image

 

posted @ 2026-11-26 22:24  千手扉间【秽土转生】  阅读(5)  评论(0)    收藏  举报