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

运行截图

1

问题

问题 1
Window 与 Button 是组合(composition,has‑a)关系。
std::vector<Button> buttons_ 存储的是 Button对象值,不是指针。
Window 对象内部直接持有 Button 实例;当 Window 对象生命周期结束析构时,vector 会自动销毁内部所有 Button 对象;Button 的生命周期完全由 Window 管理,整体‑部分同生共死,符合组合 has‑a 特征。
如果是聚合则一般存放指针,外部对象生命周期不受容器控制。

问题 2
① 如果has_button()改为 public:

优点:外部使用者可以直接查询窗口内是否存在某个按钮,外部可以复用该查询逻辑。

② public/private 决策原则:

public:类外部用户需要调用的业务接口;
private:仅类内部使用、属于实现细节;如果对外暴露可能被误用、破坏对象内部状态,则设为 private。

问题 3

接口 1:const std::string& get_label() const; 返回常量引用
性能:不拷贝字符串,直接返回内部成员的引用,性能高;
安全性:返回 const 引用,外部不能通过返回值修改对象内部的 label_,保证对象状态安全。 接口 2:std::string get_label() const; 返回值
性能:会拷贝一份完整 string 对象,存在内存拷贝开销;
安全性:返回的是副本,外部修改副本不会影响对象内部,安全性同样高

问题 4
① push_back(Button(xxx)) vs emplace_back(xxx)

push_back(Button("xxx")):先在外部创建临时 Button 对象,再把临时对象移动 / 拷贝到 vector 容器。
emplace_back("xxx"):直接在容器的内存空间原地构造 Button 对象,不需要产生临时对象,减少拷贝 / 移动,效率更高。程序改写后可以正常运行。

② std::any_of(begin,end,predicate)
功能:判断区间中**是否至少有一个元素满足谓词条件。
参数:迭代器首、尾;一元谓词(返回 bool 的可调用对象,lambda / 函数指针)。
返回:存在满足条件元素返回true,全部不满足返回false。题目改写代码可以正常工作。

③ std::find_if(begin,end,predicate)
功能:在区间查找第一个满足谓词条件的元素。
参数:首、尾迭代器;一元谓词。
返回值:返回找到元素的迭代器;没有找到返回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);
}

运行截图

2

问题

问题 1
std::vector<int> v1(5,42);:调用构造函数vector(size_t n, const T& val),创建 5 个值 42 的元素。
const std::vector<int> v2(v1);:调用拷贝构造函数,用 v1 复制构造 v2。
v1 有 5 个 42;拷贝后 v2 同样 5 个 42。

问题 2

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

问题 3
v1[0]=‑1替换成v1.at(0)=‑1效果等价。
区别:

  • []下标运算符:不做越界检查,越界直接未定义行为,程序可能崩溃。
  • .at(index):做边界检查,如果下标越界,抛出 std::out_of_range 异常。

问题 4
① 可以输出‑1。v1[0]返回内层 vector 的引用;const std::vector<int>& r = v1[0];拿到该内层对象的 const 引用,r 绑定到 v1 [0] 对象,访问末尾元素可以读到‑1。
② const &优势:不产生对象拷贝,直接引用原有对象,节省内存与拷贝开销;
限制:通过该引用不能修改容器内对象的内容(const 引用只读)。

问题 5

  1. vector 拷贝构造实现深拷贝:拷贝后两个 vector 拥有相互独立的数据缓冲区;修改一个不会影响另一个。
  2. 普通非 const vector 调用v.at(0)返回int&(可修改左值引用);
    const vector 对象调用v.at(0)返回const int&(只读常量引用)。
  3. 必须提供 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: 自赋值assign\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';
}

运行截图

3

问题

问题 1

3

隐患:

  1. new 内存分配失败会抛出异常:已经执行 delete [] 释放了原有内存,对象 pdata_变成野指针,对象处于损坏状态,异常安全不满足。

问题 2

  1. static_cast<const vectorInt*>(this)
    转换前:vectorInt* this
    转换后:const vectorInt*
    作用:给 this 指针增加 const 限定,调用 const 版本的 at () 复用边界检查逻辑,避免两份重复的边界检查代码。
  2. const_cast<int&>(...)
    转换前返回值:const int&()
    转换后:int& 普通可修改引用
    目的:剥离引用上的 const 限定,把 const 引用转为可修改引用,返回给非 const 的 at () 调用方;前提保证原对象本身不是 const 对象,否则 UB。

问题 3

非 const 对象:调用非 const 重载begin(),得到可写迭代器;
const 对象:只能调用 const 版本begin(),得到只读 const 迭代器。

②拓展思考:迭代器不一定是复杂类封装,*原始指针本身就满足迭代器概念;迭代器是一套抽象概念,不一定是 class,只要支持++、*、!=等操作就可以作为迭代器使用。

问题 4
可以替换。

std::fill_n(pdata_, n_, value);:从起始地址开始,填充 n_个 value 值,代替 for 循环赋值。
std::copy_n(vi.pdata_, vi.n_, pdata_);:复制 vi.pdata_开始 n_个元素到 pdata_,代替拷贝循环。
std::copy_n(vi.pdata_, vi.n_, ptr);:把源数组 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_;
    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 at,修正越界判断条件
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 at,复用const版本
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_;
}

//【重点修复print】逗号后**无空格**,严格匹配样例输出
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';
}

运行截图

3

问题

void set(const double *pvalue, int size);风险:
传入外部裸指针,函数只检查size参数,不检查传入指针 pvalue 是否为 nullptr;如果传入空指针,std::copy_n访问空指针,程序崩溃。
当数组double x[5],但是调用set(x, 10),虽然 size 校验会抛异常;但如果使用者传入野指针,无法检测。

优化方案:

  1. 在 set 开头增加判空:if(pvalue == nullptr) throw std::invalid_argument("nullptr pointer");
  2. C++17 以后可以改用std::span<double>接收一段连续内存,不需要 size 参数,更安全。

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

// 任务:1 实现index
inline int ContactBook::index(const std::string &name) const {
    for(int i = 0; i < (int)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;
}

运行截图

5

问题

  1. 组合关系(has‑a)使用对象值成员,整体与部分生命周期绑定;聚合多用指针。访问控制 public/private 体现封装,只对外暴露必要接口,内部实现细节隐藏。
  2. 深拷贝与浅拷贝:裸指针默认拷贝构造只复制指针值(浅拷贝,两个对象共享同一块堆内存,析构重复 delete 崩溃),必须手写拷贝构造实现深拷贝;vector 等标准容器内部已经实现深拷贝。
  3. 裸指针手动内存管理容易出现自赋值、空指针、内存泄漏、野指针;优先使用 std::vector 等容器利用 RAII 自动管理内存,异常安全。
posted @ 2026-11-26 17:48  gugama  阅读(3)  评论(0)    收藏  举报