实验3

实验任务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.是组合(has‑a)关系。buttons_存储的是Button 对象的值,不是指针。Window 对象里面直接保存各个 Button 实体。Button 的生命周期完全由 Window 管理,不能脱离 Window 独立存在。

2.has_button改成 public:
优点:外部调用者可以直接查询窗口有没有某个按钮,不用自己遍历。
风险:暴露内部实现细节;外部可以依赖这个函数,如果以后内部存储结构改动,外部代码全部失效。
public:是给外部使用者调用的功能,是类对外提供的服务,用户需要直接使用。
private:只是类内部干活用的工具函数,属于实现细节;如果开放给外部调用,容易被误用,破坏对象内部数据的正确性,就放到 private。

3.接口 1(返回 const 引用)
性能:不需要拷贝字符串,直接返回内部成员的引用,开销很小。
安全:返回 const 引用,外部不能通过返回值修改类内部 label_
接口 2(返回 string 值)
性能:会复制一份完整字符串,字符串长的时候会有拷贝开销。
安全:返回的是副本,外部拿到的是独立拷贝,完全和类内部数据隔离。

4.① 可以
push_back(Button("xxx")):先在外面构造临时 Button 对象,再把这个临时对象移动或者拷贝放进 vector 容器。
emplace_back("xxx"):直接在 vector 容器内存空间原地构造 Button 对象,不需要产生临时对象。
② 可以
std::any_of(first, last, pred)
参数:first起始迭代器,last末尾后一位迭代器,pred判断条件(lambda 或者函数)。
功能:遍历 [first,last) 区间,只要任意一个元素满足 pred 条件就返回 true;全部不满足返回 false。刚好适合判断是否存在匹配的按钮。
返回:存在满足条件元素返回 true,全部不满足返回 false。
③ 可以
参数:起始迭代器、末尾迭代器、判断谓词。
功能:遍历范围,返回第一个满足 pred 条件元素的迭代器;找不到返回end()迭代器。
返回:拿到迭代器后,如果不等于 end (),就可以调用it->click(),否则输出找不到按钮。

实验任务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);
}
  • 测试截图
    image

  • 问题
    1.构造函数,5 个;拷贝构造函数,5 个。
    2.v1.size()=2
    v2.size()=2
    v1[0].size()=3
    3.能,[]下标运算符:越界访问的时候不会检查,程序直接崩溃,不抛异常。
    .at(index):会做下标范围检查。
    4.可以输出 - 1。
    v1 [0] 是 v1 内部第一个子 vector;r 是它的 const 引用,绑定原对象,r.size () 已经更新,最后一个元素就是 - 1。
    ② 用const &接收:
    内存优势:不会拷贝整个 vector,仅仅只是一个引用,几乎不占额外内存。
    限制:通过引用 r不能修改 vector 里面的元素。

  1. 深拷贝;
    vector 调用v.at(0)返回int&;
    const 的 vector 对象调用v.at(0)返回const int&。
    必须重载。因为 const 对象只能调用 const 成员函数,如果没有 const 重载,const vector 就不能调用 at () 访问元素。

实验任务3

  • 源码
    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';
}
  • 测试截图
    image

  • 问题:
    1.运行截图:存在异常
    image

没有判断自我赋值。

2.转换前 this:vectorInt*(普通对象指针);转换后:const vectorInt *;
作用:把当前对象指针强制变成 const 对象指针,调用const 版本的 at (),复用里面下标越界检查逻辑,不用重复写一遍判断代码。
const 版本 at 返回的是const int&;const_cast把返回的const int&的 const 常量属性去掉,变成普通int&;
目的:非 const 的 at 函数需要返回普通引用,允许外部修改数组元素。
3.非 const 对象调用非 const begin/end:得到普通指针迭代器,可以修改容器里面的元素。
const 对象调用 const begin/end:得到 const 指针迭代器,只能读元素,禁止修改。
4. 可以
std::fill_n(pdata_, n_, value);:把从 pdata_开始 n_个元素全部填充 value 值,代替 for 循环赋值。
std::copy_n(vi.pdata_, vi.n_, pdata_);:从 vi.pdata_复制 vi.n_个 int,写到 pdata_,代替循环拷贝。
std::copy_n(vi.pdata_, vi.n_, ptr);:把 vi 里面 n_个数据复制到新开辟 ptr 内存,代替手动 for 循环复制。

实验任务4

  • 源码
    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_;
    int total = n_rows_ * n_cols_;
    pdata_ = new double[total];
    std::copy_n(x.pdata_, total, 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, 大小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';
}

  • 测试截图
    image

  • 问题
    1.函数只判断传入 size 参数是否等于行列乘积,没有检查传入指针指向内存实际有多少有效数据。如果外面数组空间不够,但是使用者传了错误的 size,程序会读取数组越界的内存。
    2.优化:不直接接收裸指针,改用 std::array 或者 std::vector传参。

实验任务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源码

点击查看代码
# 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();
}

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

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

  • 问题:
    修改联系人:增加接口;先 index 找到下标,直接修改phone。
    数据校验:添加的时候检查手机号格式,不合法拒绝添加,输出提示。
    异常处理:读取文件失败抛出异常。

实验总结

本次实验了解了类的组合关系、深浅拷贝,理解动态内存管理,练习标准库 vector等等。

posted @ 2026-11-22 21:06  Wenster  阅读(9)  评论(0)    收藏  举报