任务一

一、源代码

#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

三、回答问题

问题一:

  • Window与Button是组合(has‑a)关系。buttons_的类型是std::vector<Button>,保存的是Button对象的值,不是指针。Window对象创建,内部buttons_随之创建;Window销毁时,  buttons_连同内部所有Button对象一起自动销毁。Button对象完全归Window管理,生命周期完全受Window控制,符合组合关系

问题二:

  • ① 如果has_button改为公有
    优点:外部代码可以直接判断按钮是否存在,不用借助其他成员函数。
    风险:暴露内部实现细节;外部代码依赖该函数,后续修改容器会破坏外部代码;扩大对外接口,容易被误用,破坏封装。
  • ② public与private的选择
    public:是类对外提供的功能,外部用户需要调用,属于对外接口契约。
    private:只供类内部其他函数调用,属于实现细节;外部不需要使用,开放出来没有价值还可能破坏对象状态,就设置为private。遵循最小对外接口原则。

问题三:

  • 接口1:const std::string& get_label() const;
  • 接口2:std::string get_label() const;
  • 接口1(返回const引用)
    性能:无拷贝开销,直接返回内部成员的引用,效率高。
    安全:const限制外部不能修改内部字符串;但原对象销毁后引用会悬空。
  • 接口2(返回值拷贝)
    性能:会拷贝一份字符串,存在复制开销。
    安全:返回独立副本,原对象销毁副本依然有效,副本修改不会影响类内部。
    本实验场景优先接口1,兼顾性能与只读安全。

问题四:

  • ① push_back(Button(xxx))改为emplace_back(xxx)
    程序可以正常运行。
    push_back:先构造临时Button对象,再把临时对象拷贝/移动存入vector。
    emplace_back:直接在vector容器内存中原位构造Button,不产生临时对象,减少拷贝,效率更高。
  • ② std::any_of改写has_button,写法可用。
    std::any_of(起始迭代器,尾后迭代器,谓词lambda)
    功能:遍历区间,只要任意一个元素满足lambda条件就返回true;全部不满足返回false。
  • ③ std::find_if改写click_button,写法可用。
    std::find_if(起始迭代器,尾后迭代器,谓词lambda)
    功能:遍历区间,返回第一个满足条件元素的迭代器;找不到返回尾迭代器end()。判断迭代器不等于end()就执行点击,否则输出未找到。

任务二

一、源代码

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

// 使用索引+循环,遍历输出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

三、回答问题

问题一:

  • 普通构造和拷贝构造,都包含五个

问题二:

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

问题三:

  • 能,v1[0] = -1写成v1.at(0) = -1,修改效果相同。
  • []下标运算符:不做越界检查,越界后是未定义行为。
  • .at():做下标越界检查,越界抛出std::out_of_range异常。

问题四:

  • ① 能。r是原vector的const引用,只是不能通过r修改容器;原对象在别处被修改,引用可以读取到更新之后的数据。
  • ② 优势:const&不产生容器副本,节省内存。
         限制:不能通过该引用调用非const成员去修改容器,只允许读取。

问题五:

  • vector拷贝构造实现的是深拷贝,拷贝之后两份数据互相独立,修改一方不会影响另一方。
  • 普通非const的vector:at(0)返回int&;
  • const修饰vector:at(0)返回const int&。
  • 必须提供const重载版本。const对象只能调用const成员函数,没有重载会编译报错。

任务三

一、源代码

#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(int n, int value): n_{n}, pdata_{new int[n](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(const vectorInt &vi): n_{vi.n_}, pdata_{vi.pdata_} {} 
// 错误:把原指针直接赋给新指针

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

三、回答问题

问题一:

  image

  • 版本2没有检查传入的对象是否就是自己,不安全。因为如果传入的对象就是自身,那么在第一步delete[] pdata_就会销毁自身数据,导致数据丢失。

问题二:

  • static_cast<const vectorInt*>(this)
    转换前this类型:vectorInt*;
    转换后:const vectorInt*,给this增加const限定;
    目的:调用const版本at(),复用越界判断逻辑,减少重复代码。
  • const_cast<int&>()
    转换前返回值:const int&;
    转换后:int&,去掉const限定;
    目的:非const版本at需要返回可修改的引用;前提是原对象本身不是const,转换安全。

问题三:

  • 对象是否为const,决定调用哪个重载版本。普通对象调用非const成员;const对象只能调用const版本成员函数。

问题四:

  • 可以使用fill_n、copy_n替代手写循环。
  • std::fill_n(pdata_, n_, value);:从pdata_起始,把n_个元素全部赋值value。
  • std::copy_n(vi.pdata_, vi.n_, pdata_);:拷贝vi的n_个数据到pdata_,用于拷贝构造。
  • std::copy_n(vi.pdata_, vi.n_, ptr);:拷贝源对象数据到新分配的ptr内存,用于assign赋值。

任务四

一、源代码

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

三、回答问题

  • 潜在风险:double x[1000] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};后面没初始化的部分会自动补0,但也有超出风险;而double x[5] = {1, 2, 3, 4, 5};仅有5个元素,输入2 3或2 5的矩阵大小都超过了5,所以会读到越界的垃圾数据。在set()接口中的1if(size != n_rows_ * n_cols_)根本没有实际作用,输入的m和n都由操作者决定,而矩阵容量n_rows_ * n_cols_是n*m,而size也是n*m,二者一定相等,所以这个判断根本无法阻止越界。
  • 优化方案:
    task4.cpp 的 test1() 内部:
  • 1、将 double x[1000] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};改为:
      std::vector<double> x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};//顶部添加`#include <vector>`
  • 2、将所有 m1.set(x, n*m); 等调用(包括 m2、m3 的 set)统一改为:
    m1.set(x.data(), static_cast<int>(x.size()));

  image

 

任务五

一、源代码

#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_;
}
#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();
}
#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;  // 返回联系人在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;
    }

    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:int index(const std::string &name) const;实现
// 返回联系人在contacts内索引; 如不存在,返回-1
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:void ContactBook::sort();实现
// 按姓名字典序升序排序通讯录
inline void ContactBook::sort(){
	int i,j;
	Contact t("t","1");
	for(i=0;i<contacts_.size()-1;i++){
		for(j=0;j<contacts_.size()-1-i;j++){
			if(contacts_[j].get_name()>contacts_[j+1].get_name()){
				t = contacts_[j];
				contacts_[j] = contacts_[j+1];
				contacts_[j+1] = t;
			}
		}
	}
}

二、运行结果

  image

posted on 2026-11-26 22:54  lamm40  阅读(3)  评论(0)    收藏  举报