实验三

实验三

任务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_ 的声明方式 (值还是指针) 和对象生命周期的管理方式来回答。
是组合(has‑a)关系。
std::vector(Button) buttons_ 存储的是 Button 对象的值,而不是指针。Window 对象内部直接拥有 Button 实例;当 Window 生命周期结束销毁时,容器内全部 Button 对象会随同 Window 一起销毁;Button 对象完全归 Window 所拥有,符合组合 “整体拥有部分,部分生命周期依附于整体” 的特征。
问题 2:bool has_button (const std::string &label) const; 被设计为私有。思考并回答:
① 若将其改为公有接口,有何优点或风险?
优点:外部代码可以直接调用判断按钮是否存在,外部调用更加方便。
风险:暴露类内部实现细节;外部代码会依赖容器的内部实现,如果后续修改类内部逻辑,外部调用代码就会出错,破坏封装性。
② 设计类时,如何决策一个成员函数应为 public 还是 private?(可从 “用户是否需要”、“是否仅为内部实现细节”、“是否易破坏对象状态” 等角度分析。)
public:对外提供给类外部用户必须调用的功能接口;
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;
性能:返回值会触发字符串拷贝,带来内存复制开销;
安全性:返回字符串副本,外部修改副本不会影响对象内部成员,安全性同样很高,但是性能较差。
问题 4:标准库探索
① 把 window.hpp 中所有 xx.push_back (Button (xxx)) 改成 xx.emplace_back (xxx),观察程序是否正常运行;查阅资料,回答两种写法的差别。
修改后程序可以正常运行。
push_back (Button (xxx)):先创建临时 Button 对象,再把临时对象拷贝 / 移动存入 vector 容器;
emplace_back (xxx):直接在 vector 容器的内存空间上原地构造 Button 对象,省去临时对象的拷贝、移动操作,执行效率更高。
② 用标准库改写 window::has_button () 实现,这样编写是否可以?查阅资料,简述 std::any_of () 功能、参数和返回值意义。
改写后代码可以正常工作。
std::any_of (begin, end, pred)
参数:迭代器区间 [begin, end),判断条件的谓词函数 pred;
返回值:区间中只要任意一个元素满足谓词条件就返回 true;全部元素都不满足条件则返回 false。
③ 用标准库改写 window::click_button () 实现,这样编写是否可以?查阅资料,简述 std::find_if () 功能、参数和返回值意义。
改写后代码可以正常工作。
std::find_if (begin, end, pred)
参数:迭代器区间 [begin, end),判断条件的谓词 pred;
返回值:返回第一个满足谓词条件元素的迭代器;没有匹配元素,返回容器 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::vectorv1(5,42); const std::vector v2(v1);
std::vector v1 (5,42):值初始化构造,创建 vector 对象,内部 5 个元素全部初始化为 42,v1 含有 5 个 42。
const std::vector v2 (v1):调用拷贝构造函数,用 v1 复制生成 v2,v2 含有 5 个 42。
问题 2:测试模块 2 中这两行代码执行后,v1.size () 、v2.size () 、v1 [0].size () 分别是多少?
std::vector<std::vector> v1{{1, 2, 3}, {4, 5, 6, 7}};
const std::vector<std::vector> v2(v1);
v1.size() = 2;v2.size() = 2;v1[0].size() = 3。
问题 3:测试模块 1 中,把 v1 [0] = -1; 写成 v1.at (0) = -1; 能否实现同等效果?两种用法有何区别?
索引合法的前提下两者效果完全相同。
operator []:不做越界检查,越界发生未定义行为,运行速度快。
at ():执行边界检查,如果索引越界会抛出 std::out_of_range 异常,安全性更高。
问题 4:测试模块 2 中执行 v1 [0].push_back (-1); 后
①用以下两行代码,能否输出 - 1? 为什么?
const std::vector &r = v1 [0];
std::cout << r [r.size ()-1]<<std::endl;
可以输出 - 1。v1 [0] 返回内层 vector 的引用,const 引用 r 绑定到该对象,可以正常访问容器已经新增的末尾元素。
② r 定义成用 const & 类型接收返回值,在内存使用上有何优势?有何限制?
优势:不会拷贝整个 vector 容器,直接绑定原对象,节省内存,避免拷贝开销。
限制:不能通过 r 修改容器内的元素,const 引用只读。
问题 5:观察程序运行结果,反向分析、推断:
① 标准库模板类 vector 的复制构造函数实现的是深拷贝还是浅拷贝?
vector 拷贝构造实现深拷贝,拷贝之后两个对象拥有相互独立的数据缓冲区,修改原对象不会影响副本。
② vector::at () 接口思考:当 v 是 vector 时,v.at (0) 返回值类型是什么?当 v 是 const vector 时,v.at (0) 返回值类型又是什么?据此推断标准库 std::vector 的 at () 接口是否必须提供带 const 修饰的重载版本?
普通 vector对象调用 at (0) 返回 int&,可读写引用;
const vector对象调用 at (0) 返回 const int&,只读引用。
必须提供 const 重载版本,const 对象只能调用 const 成员函数,没有 const 重载,const 对象将无法调用 at () 访问容器元素。

任务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:
image

缺陷:

  1. 缺少自赋值判断 if (this == &vi)。当执行 x.assign (x),先执行 delete [] 释放自身内存,后续读取 vi.pdata_访问已经释放的内存,属于野指针,程序直接崩溃。
  2. 先释放原有内存,再 new 分配内存;如果 new 内存分配抛出异常,对象内部 pdata_成为悬空指针,对象处于非法状态,对象析构时会发生二次 delete。

问题 2:
static_cast<const vectorInt*>(this)
转换前 this 类型:vectorInt;
转换后 this 类型:const vectorInt;
作用与目的:把当前对象指针转为 const 对象指针,调用 const 版本的 at () 函数,复用边界检查逻辑,消除重复代码。
const_cast<int&>
转换前返回类型:const int&;
转换后返回类型:int&;
作用与目的:去除 const 限定,得到可写引用;前提原始对象本身不是 const,否则会产生未定义行为。

问题 3:
auto it1 = v1.begin (); // 调用非 const 版本 begin (),返回 int;普通非 const 容器对象,获取可修改的迭代器,可以修改容器内元素。
auto it2 = v2.begin (); // 调用 const 版本 begin (),返回 const int;const 只读容器对象,获取只读迭代器,禁止修改容器元素。

问题 4:
可以替换,和手写 for 循环功能等价。
更新 1 std::fill_n (pdata_, n_, value):从 pdata_起始位置开始,连续 n_个内存单元全部填充 value 数值。
更新 2 std::copy_n (vi.pdata_, vi.n_, pdata_):从源 vi.pdata_拷贝 n_个 int 元素,复制到目标 pdata_内存地址。
更新 3 std::copy_n (vi.pdata_, vi.n_, ptr):将 vi 对象中 n_个数据拷贝到新分配的 ptr 缓冲区。

任务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 <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];
}

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

  • 运行截图
    截图20261126220331

任务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(补全index和sort)源代码
点击查看代码
#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函数========
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;
}

  • 运行截图
    3861631-20261126153005411-25993113
posted @ 2026-11-26 22:10  徐之恒  阅读(8)  评论(0)    收藏  举报