实验3

task1

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

运行结果截图:

屏幕截图 2026-11-25 215939

问题一:
是。Button 对象是按值直接存储在 vector 中的,而不是指针(Button*)或引用;
对象生命周期管理方面,Button 的生命周期完全由 window 管理。Window 不需要(也无法)手动去 delete 这些按钮,window 析构时,vector 会自动析构里面的所有 Button 对象。
问题二:
①
优点:方便调用方做条件判断。
风险:如果日后 window 的内部存储结构发生变化,公有接口将被迫保留,从而限制重构的灵活性

② 接口的最小化原则,暴露越少的接口,类的封装性越好,日后修改内部实现时的成本越低。只暴露真正需要完成用例的方法。

能够修改核心状态的方法通常需要严格控制

问题三:

接口1:
◦ 性能优。没有发生任何内存拷贝,只返回了内部成员 label_ 的引用地址,开销小。
◦ 安全性:外部可以只读访问内部字符串,但如果持有这个引用的 Button 对象被销毁了,这个引用就变成了野引用。
• 接口2:
◦ 性能低。每次调用都会产生一次拷贝。对于长字符串,拷贝开销显著。
◦ 安全性高。返回的是内部数据的独立副本,外部操作副本完全不会影响原对象,没有悬垂引用风险。

问题四:

可以正常运行。

② 可以。

 功能:判断给定区间 [first, last) 内是否存在至少一个元素满足一元谓词。返回值:bool,如果存在返回 true,否则 false。

③
可以。
功能:在区间 [first, last) 内查找第一个满足一元谓词 p 的元素。
参数:迭代器 first、last,以及 p。
返回值:返回指向第一个满足条件的元素的迭代器。如果没找到,则返回 last。
通过 auto it = std::find_if(...) 获取到目标迭代器后,判断 it != buttons_.end()。如果存在,直接通过 it->click() 调用。

task2

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

运行截图

捕获

 问题一:

第一行代码完成了普通构造。
•第二行代码完成了拷贝构造。
v1 包含 5 个值为 42 的数据项;v2 也包含 5 个值为 42 的数据项。

 问题二:

2

2

3

问题三:能

区别:
operator[]:不进行边界检查。它直接通过指针偏移访问内存,效率高。如果索引越界,会导致未定义行为。
at():进行严格的边界检查。如果索引越界,at() 会抛出一个 std::out_of_range 类型的异常,程序可以通过 try-catch 捕获该异常,从而提升代码的健壮性和安全性,但会带来小的性能开销。

问题四

能输出 -1。
 原因:v1[0].push_back(-1); 将 v1 的第一个内部 vector 更新为 {1, 2, 3, -1},此时该内部 vector 的大小变为 4。r 作为 v1[0] 的引用,随之更新。r.size() - 1 的值为 3,因此 r[3] 合法访问了最后一个元素,输出 -1。

 优势:使用引用 & 可以避免拷贝。使用引用仅仅是一个别名),不产生任何内存分配开销,效率高。
限制:
 由于带有 const 修饰,r不能修改其绑定的对象。
如果 v1[0] 这个元素被销毁,r 就会变成野引用,此时再使用 r 会导致未定义行为。

问题五:

深拷贝;int&;const int&

task3

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

 运行截图:

屏幕截图 2026-11-25 224525

问题一:

方案2没有检查传入的对象是否是自己。如果传入的对象就是自身,那么在delete[] pdata_就会销毁自身数据,导致数据丢失。

 问题二

作用:将当前的非常量对象指针转换为常量对象指针。

转换前:vectorInt*。
转换后:const vectorInt*。
转换目的:为了调用 const 版本的 at(int index) const 函数。可以复用const 版本的代码,避免在两个版本中写重复的逻辑,符合代码复用原则。

作用:去除常量属性,将常量引用转换为非常量引用。

转换前:const int& 。
转换后:int&。
转换目的:当前调用者是非 const 对象,期望通过 at() 获得一个可修改的引用,以便执行如 v.at(0) = 10; 这样的赋值操作。

问题三:

v1.begin():调用的是非 const 版。
v2.begin():调用的是 const 版本。

非 const 版本适用于需要修改容器内元素的场景。
const 版本适用于只读遍历或容器本身是 const 的。

问题四:

可行

这三行代码均调用了 C++ 标准库 中的泛型算法,替代了原本手动的 for 循环,在语义表达上更加清晰:
std::fill_n(first, count, value):在区间起始点 first 开始,将接下来的 count 个元素赋值为 value。用于构造函数中初始化默认值。
std::copy_n(first, count, result):从源区间起始点 first 开始,复制 count 个元素到目标起始点 result。用于拷贝构造函数和赋值运算符中的深拷贝操作。

task4

#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_;    // 数据区
};
#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';
}
#include "matrix.h"

#include <algorithm>
#include <cstdlib>
#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) {
    pdata_ = new 
double[x.n_rows_*x.n_cols_];
    for(auto i = 0
; i < x.n_rows_*x.n_cols_; ++i)
        pdata_[i] = x.pdata_[i];
}
// 待实现:释放指针指向的内存资源
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];
}
// 待实现:返回矩阵对象索引(i,j)对应的数据项引用(越界则抛出异常)
// 参考前一个接口和task3的问题2
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++){
            std::cout << pdata_[i * n_cols_ + j] << " ";  }
        std::cout << "\n";
    }
}

运行截图:

屏幕截图 2026-11-25 230634

接口设计缺陷:set(const double *pvalue, int size) 接口仅接收一个裸指针 pvalue 和期望拷贝的元素个数 size。接口内部只校验了 size 是否等于矩阵元素总数 n_rows_ * n_cols_,但无法校验指针 pvalue 实际指向的内存空间是否足够大。

可以使用标准库容器作为参数

 

 

task5

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

 

#pragma once

#include "contact.hpp"

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <cstddef> // 使用 size_t

// 通讯录类
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; // 显示所有联系人
    std::size_t size() const; // 无符号整数

private:
    int index(const std::string &name) const;  // 返回联系人在vector内索引,如不存在,返回-1
    void sort(); // 按姓名字典序升序排序通讯录

    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;
    }
    // 使用 erase-remove 惯用法或直接通过迭代器删除
    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(const auto &c: contacts_) {
        c.display(); 
        std::cout << '\n';
    }
}

inline std::size_t ContactBook::size() const {
    return contacts_.size();
}

// 待补足1:返回联系人在contacts内索引; 如不存在,返回-1
inline int ContactBook::index(const std::string &name) const {
    // 优化:使用 std::size_t 避免 int 与 size_t 的有符号/无符号比较警告
    for(std::size_t i = 0; i < contacts_.size(); ++i) {
        if(contacts_[i].get_name() == name) {
            return static_cast<int>(i); // 强制转换回 int 以匹配返回类型
        }
    }
    return -1;
}

// 待补足2:按姓名字典序升序排序通讯录
inline void ContactBook::sort() {
    // 优化:废弃低效、易错的冒泡排序,改用标准库 std::sort
    // Contact 类需提供 get_name(),如果是 C++11 及以上,这里使用 Lambda 表达式
    std::sort(contacts_.begin(), contacts_.end(), 
        [](const Contact &a, const Contact &b) {
            return a.get_name() < b.get_name();
        }
    );
}

运行截图:

屏幕截图 2026-11-26 003715

 

posted @ 2026-11-26 00:38  HU00000  阅读(9)  评论(0)    收藏  举报