实验三

实验任务一

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

  

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

 

#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-20 113145

问题一

是组合关系,private std::vector<Button> buttons_,存储的是Button 对象的值。Window 对象内部直接包含 Button 实例;Button 对象生命周期完全受 Window 管控,Window 销毁时内部所有 Button 对象随之销毁,符合组合关系。

问题二:

优点:外部代码可以直接调用判断按钮是否存在

风险:暴露内部实现细节,如果后期修改内部存储结构,外部代码全部失效,破坏封装。

 public:类的外部用户需要调用的功能,对外提供服务接口。

private:仅类内部使用,属于实现细节;如果对外暴露容易被误用、破坏对象内部状态,则必须私有。

问题三:

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

性能:返回常量引用,不拷贝字符串,直接返回内部成员的别名,开销很小。安全:const 引用,外部不能修改内部字符串,只读

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

性能:返回值,会调用 string 拷贝构造,生成副本,存在内存拷贝开销;字符串越大开销越高。

安全:返回副本,外部拿到的是拷贝,完全和对象内部隔离,外部修改副本不会影响对象内部

问题四:

1.可以正常运行

push_back(Button(xxx)):先在外部构造临时 Button 对象,再把临时对象拷贝存入 vector 容器。

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

2.可以正常运行

参数:first,last迭代器区间;pred谓词(返回 bool 的函数 /lamdba)

 功能:遍历区间,只要任意一个元素满足谓词返回 true,整体返回 true;全部不满足返回 false。

3.可以正常运行

参数:迭代器区间、判断谓词

功能:查找区间内第一个满足谓词条件的元素。

返回值:找到返回该元素迭代器;找不到返回end()迭代器。

实验任务2

#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-24 140323

问题一

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

const std::vector<int> v2(v1);:拷贝构造函数,用 v1 复制生成 v2;v2 有 5 个 42。

问题二

v1.size() = 2;v2.size() =2;v1[0].size() =3

问题三

可以实现同等赋值效果

operator[]:不做越界检查,下标越界直接未定义行为,程序可能直接崩溃。

.at(index):做下标越界检查,更安全

问题四

能

v1[0]返回第一个子 vector 引用,const std::vector<int>& r绑定这个引用;r 引用的是 v1 内部真实对象,r[r.size()-1]访问新增的末尾元素 - 1。

优势:不会拷贝整个 vector,节省内存。

限制:不可用r修改元素。

问题五

深拷贝

普通版本返回int&,const版本返回const int&

必须提供,如果没有const重载,const对象无法调用at()访问元素

实验任务三:

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

  

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

  运行截图

屏幕截图 2026-11-24 141306

 

问题一:

隐患:没有判断自赋值

当执行x.assign(x)时:首先执行delete[] pdata_释放自己的内存,后续访问vi.pdata_,vi 就是 * this,内存已经被释放,访问已经释放的野指针,产生未定义行为。

问题二

1.转换前:this是普通对象指针。

转换后:const vectorInt*,给 this 指针增加 const 修饰

目的:调用const 版本 at (),复用越界检查逻辑,避免重复写一遍越界判断代码。

2.转换前返回值:const int&

转换后:int&

目的:把 const 引用去除 const 限定,返回可写引用

问题三

1.vectorInt v1(5); auto it1 = v1.begin();调用非 const 版本 begin () 返回int*

const vectorInt v2(5); auto it2 = v2.begin();调用const 版本 begin () 返回const int*

场景:

普通对象:调用非 const begin/end

const 对象、const 引用对象:调用 const begin/end,只能读不能修改元素。

问题四

可以,但要引入头文件<algorithm>

更新 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):源 vi.pdata_复制 vi.n_个元素到新分配内存 ptr。

实验任务四

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

  

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

  

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

  运行截图

屏幕截图 2026-11-24 143239

 

问题

存在潜在风险:编译器无法知道传入数组的真实长度。

优化方案:改用 std::vector<double>做参数,void set(const std::vector<double>& v);内部读取 v.size (),不需要手动传 size 参数,消除人为传错 size 风险。

实验任务五:

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

  

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

  

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

  运行结果

屏幕截图 2026-11-24 143636

思考

1.修改联系人:新增modify(name,newPhone)接口,内部调用 index 查找,修改对应 Contact;

2.数据校验:手机号格式校验,姓名非空校验;非法输入显示异常。

3.持久化:读写文件,程序退出保存联系人,启动加载联系人

4.模糊搜索:用 string::find 实现部分匹配

5.分组:新增 Group 类,ContactBook 组合多个 Group 对象; 遵循开闭原则,尽量不改动原有接口,新增成员函数完成扩展

实验总结

本次实验我深刻体会到了const成员函数重载:普通对象调用非 const 版本,const 对象调用 const 版本;利用static_cast+const_cast复用逻辑,消除重复代码。

 

posted @ 2026-11-24 14:44  tyyyyyxy  阅读(10)  评论(0)    收藏  举报