实验三

任务一:

代码部分:

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

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 <iostream>
#include <vector>
#include <algorithm>
#include "button.hpp"

// 窗口类
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;

private:
    std::string title;
    std::vector<Button> buttons;
};

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

结果截图:

实验三—任务1—结果1

问题回答:

问题一:是组合关系,window包含button对象,同时二者生命周期一致

问题二:

(1):改为公有,会破坏window类的封装性,同时会存在window内部重复检查的问题,最后是混合动作型和查询型接口,职责不清晰

(2):在设计类的过程中,默认设为 private,只有明确需要对外提供的功能才设为 public,也就是说客户需要的功能设置为public,符合自然行动处理流程的设置为public(涉及业务逻辑的完整性),public需要稳定和简洁的公共接口

问题三:

性能方面:

接口一const std::string& get_label() const;  0拷贝(直接返回内部字符串的引用,无额外内存分配),高性能(无论字符串多大,返回成本恒定(一个指针大小))

接口二const std::string get_label() const;  拷贝构造(返回时创建字符串副本,可能触发内存分配),性能损耗(字符串越大,拷贝成本越高)

安全方面:

接口一const std::string& get_label() const;  悬挂引用风险(如果Button对象被销毁,返回的引用将无效),线程安全(多线程环境下可能读取到正在修改的数据)

接口二const std::string get_label() const;  值语义安全(返回独立副本,生命周期与原始对象无关),线程安全(调用者获得完全独立的数据副本)

总结: Button生命周期通常由Window管理,悬挂引用风险可控; label在构造后通常不变,线程安全问题有限

问题四:

结果截图:

实验三—任务1—结果2

结果依然正常运行和输出,二者差异在于push_back是有一个临时对象进行拷贝或移动,但是emplace_back是直接在vector的内存空间中构造button对象(该代码使用完美转发技术)节省了内存分配并提高了性能

 

任务二:

代码部分:

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

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.at(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: "; output3(v1);
    std::cout << "v2: "; output3(v2);

    v1.at(0).push_back(-1);

    std::cout << "**********修改v1[0]后**********\n";
    std::cout << "v1: \n";  output3(v1);
    std::cout << "v2: \n";  output3(v2);
}

// 使用xx.at()+循环输出vector<int>数据项
void output1(const std::vector<int> &v) {
    if(v.size() == 0) {
        std::cout << '\n';
        return;
    }
    
    std::cout << v.at(0);
    for(auto i = 1; i < v.size(); ++i)
        std::cout << ", " << v.at(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

问题回答:

问题1:

std::vector<int> v1(5, 42);  完成的是带参数的构造函数
const std::vector<int> v2(v1);  完成的是拷贝构造函数(深拷贝)
v1 构造后包含 5 个值为 42 的数据项v,2 构造后也包含 5 个值为 42 的数据项
 
问题2:
v1.size() = 2  v2.size() = 2  v1[0].size() = 3
 
问题3:
能实现同等效果,区别在at()有边界检查,但是性能上要更慢(但是安全性更高),operator[]没有边界检查,性能上更快
 
问题4:
(1)可以输出-1,执行 v1.at(0).push_back(-1); 后v1[0]的内容从【1,2,3】变成了【1,2,3,-1】
std::vector<1nt>&r = v1.at(0):执行引用绑定,r和v1[0]指向同一个vector对象,通过r访问就是直接访问v1[0]
std::cout << r.at(r.size()-1),size是4,4-1=3,也就是通过r访问索引为3的元素,也就是最后一个元素-1所以能输出-1
(2)优势:零拷贝开销(不创建副本,直接引用原对象),避免不必要的构造/析构(没有临时对象产生)
限制:只能进行只读操作,没法通过r进行改动,需要注意生命周期
 
问题5:
(1)从第一个测试结果来看修改v1[0] 后,v2的内容保持不变说明v1和v2拥有独立的内存空间,是深复制
从第二个测试结果来看修改v1[0]后(即添加元素-1),v2[0]的内容保持不变说明内外层vector都是独立的,是深复制
(2)当 v 是 vector<int> 时, v.at(0) 返回值类型是非常量引用int&
当 v 是 const vector<int> 时, v.at(0) 返回值类型是常量引用const int&
据此推断 at() 必须提供带 const 修饰的重载版本以确保const对象的元素不被修改
 
任务三:
代码部分:
vectorInt.hpp:
#pragma once

#include <iostream>

// 动态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 *ptr;  // 数据区
};

vectorInt::vectorInt():n{0}, ptr{nullptr} {
}

vectorInt::vectorInt(int n_): n{n_}, ptr{new int[n]} {
}

vectorInt::vectorInt(int n_, int value): n{n_}, ptr{new int[n_]} {
    for(auto i = 0; i < n; ++i)
        ptr[i] = value;
}

vectorInt::vectorInt(const vectorInt &vi): n{vi.n}, ptr{new int[n]} {
    for(auto i = 0; i < n; ++i)
        ptr[i] = vi.ptr[i];
}

vectorInt::~vectorInt() {
    delete [] ptr;
}

int vectorInt::size() const {
    return n;
}

const int& vectorInt::at(int index) const {
    if(index < 0 || index >= n) {
        std::cerr << "IndexError: index out of range\n";
        std::exit(1);
    }

    return ptr[index];
}

int& vectorInt::at(int index) {
    if(index < 0 || index >= n) {
        std::cerr << "IndexError: index out of range\n";
        std::exit(1);
    }

    return ptr[index];
}

vectorInt& vectorInt::assign(const vectorInt &vi) { 
    if(this == &vi) 
        return *this;

    int *ptr_tmp;
    ptr_tmp = new int[vi.n];
    for(int i = 0; i < vi.n; ++i)
        ptr_tmp[i] = vi.ptr[i];
    
    delete[] ptr;
    n = vi.n;
    ptr = ptr_tmp;
    return *this;
}

int* vectorInt::begin() {
    return ptr;
}

int* vectorInt::end() {
    return ptr+n;
}

const int* vectorInt::begin() const {
    return ptr;
}

const int* vectorInt::end() const {
    return ptr+n;
}
task3.cpp:
#include "vectorInt.hpp"
#include <iostream>

void test1();
void test2();
void output1(const vectorInt &vi);
void output2(const vectorInt &vi);

int main() {
    std::cout << "测试1: \n";
    test1();

    std::cout << "\n测试2: \n";
    test2();
}

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

// 使用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';
}

结果截图:

实验三—任务3—结果1

问题回答:

问题1:

对比1:

  原版本:

  if(this == &vi)

  return *this; //  自赋值检查

  版本2:

  // 缺失自赋值检查
  delete[] ptr; 
  n = vi.n; // vi.n 已经被破坏
  ptr = new int[n]; // 分配新内存
  for(int i = 0; i < n; ++i)
  ptr[i] = vi.ptr[i]; // 从已删除的内存读取数据

对比2(包含两处对比,分别是内存释放的先后和是否采取临时变量):

  原版本:

  int *ptr_tmp = new int[vi.n]; // 先分配新内存
  for(int i = 0; i < vi.n; ++i) // 拷贝数据到临时内存
  ptr_tmp[i] = vi.ptr[i];
  ptr = ptr_tmp;//使用了临时变量
  delete[] ptr; // 最后释放旧内存 

  版本2:

  delete[] ptr; //  先释放旧内存
  n = vi.n;
  ptr = new int[n]; //直接更新,ptr变为野指针,n变为错误值

 

问题2:

(1):static_cast<const vectorInt*>(this) 的作用是将非常量指针vectorInt*转化成常量指针const vectorInt*,目的是为了调用const版本的at()方法,将this从vectorInt* 转为const vectorInt*这样->at(index) 就会调用const int& at(int index) const 版本,避免在非const方法中直接实现相同逻辑

(2):const_cast<int&> 的作用是将const版本at()的返回值const int&转换成非const版本at()需要的返回值int&,目的是为了移除const限定符,匹配返回类型

 

问题3:

(1):

vectorInt v1(5);
const vectorInt v2(5);
auto it1 = v1.begin(); // 调用int* begin()
auto it2 = v2.begin(); // 调用const int* begin() const
 
int* begin()适用于修改元素,使用修改性算法,遍历并修改的场景
const int* begin() const适用于只读访问,常量对象遍历(只读遍历),使用只读算法的场景
 
问题4:可以
代码作用(截图中注释):
vectorInt::vectorInt(int n_, int value): n{n_}, ptr{new int[n_]} {
std::fill_n(ptr, n, value); // 功能:创建大小为n_的数组,并将所有元素初始化为value
    // 步骤:
    // 1. n{n_}: 设置元素个数为n_
    // 2. ptr{new int[n_]}: 分配n_个int的内存块
    // 3. std::fill_n: 将整个内存块填充为指定值value
}
vectorInt::vectorInt(const vectorInt &vi): n{vi.n}, ptr{new int[n]} {
std::copy_n(vi.ptr, vi.n, ptr); // 功能:深拷贝构造,创建vi的完整独立副本
    // 步骤:
    // 1. n{vi.n}: 复制源对象的元素个数
    // 2. ptr{new int[n]}: 分配相同大小的新内存块
    // 3. std::copy_n: 将源对象的所有元素值复制到新内存块
    // 效果:新对象与源对象数据相同但内存独立
}
vectorInt& vectorInt::assign(const vectorInt &vi) {
if(this == &vi)
return *this;// 自赋值检查:源和目标相同则直接返回
int *ptr_tmp;
ptr_tmp = new int[vi.n];// 步骤1:分配新内存块
std::copy_n(vi.ptr, vi.n, ptr_tmp); // 步骤2:复制源数据到临时内存
delete[] ptr;// 步骤3:释放旧内存
n = vi.n;// 步骤4:更新元素个数
ptr = ptr_tmp;// 步骤5:指向新内存
return *this;// 功能:安全的赋值操作,实现深拷贝赋值
}

 

任务四:

代码部分:

matrix.hpp:
#pragma once

#include <iostream>
#include <algorithm>
#include <cstdlib>

// 类Matrix声明
class Matrix {
public:
    Matrix(int rows_, int cols_, double value = 0); // 构造rows_*cols_矩阵对象, 初值value
    Matrix(int rows_, double value = 0);    // 构造rows_*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 *ptr;    // 数据区
};
matrix.cpp:
#include "matrix.hpp"
#include <iostream>
#include <algorithm>
#include <cstdlib>

// 构造rows_*cols_矩阵对象, 初值value
Matrix::Matrix(int rows_, int cols_, double value) 
    : n_rows(rows_), n_cols(cols_), ptr(new double[rows_ * cols_]) {
    std::fill_n(ptr, n_rows * n_cols, value);
}

// 构造rows_*rows_方阵对象, 初值value
Matrix::Matrix(int rows_, double value) 
    : n_rows(rows_), n_cols(rows_), ptr(new double[rows_ * rows_]) {
    std::fill_n(ptr, n_rows * n_cols, value);
}

// 深复制
Matrix::Matrix(const Matrix &x) 
    : n_rows(x.n_rows), n_cols(x.n_cols), ptr(new double[x.n_rows * x.n_cols]) {
    std::copy_n(x.ptr, n_rows * n_cols, ptr);
}

// 析构函数
Matrix::~Matrix() {
    delete[] ptr;
}

// 按行复制pvalue指向的数据,要求size=rows*cols,否则报错退出
void Matrix::set(const double *pvalue, int size) {
    if (size != n_rows * n_cols) {
        std::cerr << "SizeError: input size does not match matrix dimensions\n";
        std::exit(1);
    }
    std::copy_n(pvalue, size, ptr);
}

// 矩阵对象数据项置0
void Matrix::clear() {
    std::fill_n(ptr, n_rows * n_cols, 0.0);
}

// 返回矩阵对象索引(i,j)对应的数据项const引用(越界则报错后退出)
const double& Matrix::at(int i, int j) const {
    if (i < 0 || i >= n_rows || j < 0 || j >= n_cols) {
        std::cerr << "IndexError: matrix index out of range\n";
        std::exit(1);
    }
    return ptr[i * n_cols + j];
}

// 返回矩阵对象索引(i,j)对应的数据项引用(越界则报错后退出)
double& Matrix::at(int i, int j) {
    if (i < 0 || i >= n_rows || j < 0 || j >= n_cols) {
        std::cerr << "IndexError: matrix index out of range\n";
        std::exit(1);
    }
    return ptr[i * n_cols + 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) {
        std::cout << at(i, 0);
        for (int j = 1; j < n_cols; ++j) {
            std::cout << ", " << at(i, j);
        }
        std::cout << '\n';
    }
}
task4.cpp:
#include <iostream>
#include <cstdlib>
#include "matrix.hpp"

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

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, 3, -1);
    const Matrix m2(m1);
    
    std::cout << "矩阵对象m1: \n";   m1.print();
    std::cout << "矩阵对象m2: \n";   m2.print();

    m1.clear();
    m1.at(0, 0) = 1;

    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()) {
        std::cerr << "IndexError: row index out of range\n";
        exit(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';
}

结果截图:

实验三—任务4—结果1

 

任务五:

代码部分:

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

int main() {
    test();
}
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;   // 必填项
};

Contact::Contact(const std::string &name_, const std::string &phone_):name{name_}, phone{phone_} {
}

const std::string& Contact::get_name() const {
    return name;
}

const std::string& Contact::get_phone() const {
    return phone;
}

void Contact::display() const {
    std::cout << name << ", " << phone;
}
contactBook.hpp:
# pragma  once

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include "contact.hpp"

// 通讯录类
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;  // 返回联系人在contacts内索引,如不存在,返回-1
    void sort(); // 按姓名字典序升序排序通讯录

private:
    std::vector<Contact> contacts;
};

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

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

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

void ContactBook::display() const {
    for(auto &c: contacts) {
        c.display(); 
        std::cout << '\n';
    }
}

size_t ContactBook::size() const {
    return contacts.size();
}

// 待补足1:int index(const std::string &name) const;实现
// 返回联系人在contacts内索引; 如不存在,返回-1
int ContactBook::index(const std::string &name) const {
    for (size_t i = 0; i < contacts.size(); ++i) {
        if (contacts[i].get_name() == name) {
            return static_cast<int>(i);
        }
    }
    return -1;
}

// 待补足2:void ContactBook::sort();实现
// 按姓名字典序升序排序通讯录
void ContactBook::sort() {
    std::sort(contacts.begin(), contacts.end(), 
        [](const Contact& a, const Contact& b) {
            return a.get_name() < b.get_name();
        });
}

结果截图:

实验三—任务5—结果1

 

posted @ 2025-11-26 05:46  栖月水生  阅读(0)  评论(0)    收藏  举报