实验三

任务一:

1.源代码:

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

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

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

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

2.实验测试代码运行结果如下:

屏幕截图 2025-11-19 083351

3.问题回答:

问题一:是;

问题二:(1)优点:共有接口增多,便于类对象在外部直接使用;

      风险:如果后续使用该接口过多,如果需要更改这个接口,会导致在外部调用此接口的地方需要对应更改,不利于维护代码;其次,会由于多次调用导致代码重复,累赘,而且在项目复杂情况下,可能会写出具有同样功能的代码,不利于代码的简洁性。

    (2)当内部类对于该接口调用较多时,可以封装在内部去使用,即private;根据用户需求,用户不需要去知道代码内部细节,只需要能够正常使用,即可使用public去直接灵活的调用接口;当然,如果类外部使用该方法较少时,也可以使用public,便于灵活使用;如果接口返回对象容易改变的话,可能共有的方法不会很合适。

问题三:接口1返回引用类型,接口2返回普通类型;对于接口1,是在原参数存储地址下更改存储信息,后者类似移动构造,使用另外的存储地址;因此,前者可以改变原变量信息,而后者可以选择性改变(自己赋值给自己),所有相较而言后者更安全。简而言之,前者性能强,后者更安全。

问题四:能正常运行,前者类似复制构造了对象,将其放入容器中;后者是向容器传递生成对象的参数,不会额外占用内存空间(不复制),在容器中构造对象。

任务二:

1.源代码:

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

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.实验测试代码运行结果如下:

屏幕截图 2025-11-21 154743

3.问题回答:

问题一:

  分别完成了带参数构造vector容器、以及复制构造;v1和v2都包含5个值为42的数据项。

问题二:

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

问题三:

  能实现同等效果,但是两者还是有差异的,使用at()方法可以自动检查索引边界,而[]是不会检查的。

问题四:

  (1)能输出-1;因为第一行代码能够给r返回一个v1的第一个vector容器(原v1含有2个vector容器),这样在执行第二行代码时,调用at()方法即相当于在一个vector容器中取对应索引值(最后一个)。

  (2)优势:和v1.at(0)绑定,类似指针,所以占用内存资源少,能够提高性能;限制:不能对r进行赋值等改变操作,也就是不能通过r去改变v1的内部数据,而且随着v1的生命周期结束,r也变为空引用。

问题五:

  (1)深复制;

  (2)int&类型;const int&类型;必须提供,否则非const对象会更改const对象。

任务三:

1.源代码:

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

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

2.实验测试代码运行结果如下:

屏幕截图 2025-11-21 165141

3.问题回答:

问题一:

  版本1是先进行分配内存空间操作,后进行复制操作,最后删除,而版本2是先将原来的内存空间给删除了,后进行分配空间和复制操作,如果在内存空间分配失败情况下,第二个版本就会事先丢失原来的数据,及其不安全。

问题二:

  (1)将this进行类型转化(非const对象转换为const对象);转换前:vectorInt*,转换后:cosnt vectorInt*;便于非const对象通过转换成const对象后可以调用const函数方法。

  (2)将const对象转换为非const对象;转换前:const int&;转换后:int&;使得原本只读的引用变成可写的。

问题三:

  (1)v1调用非const版本,v2调用const版本;在需要修改容器元素时,使用非const重载,在只用可读或者访问操作时,使用非const重载。

  (2)迭代器可能类似于指针对象。

问题四:

  可以,第一行:填充指针对应的n个位置元素为value ;第二行:将vi.ptr容器的vi.n个元素复制到另一个容器ptr中 ;第三行:将vi.ptr容器的vi.n个元素复制到另一个容器ptr_tmp中。

任务四:

1.源代码:

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

(2)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;    // 数据区
};

(3)matrix.cpp:

#include <iostream>
#include <algorithm>
#include "matrix.hpp"


Matrix::Matrix(int rows_, int cols_, double value): n_rows{rows_},n_cols{cols_},ptr{new double[rows_*cols_]}{
    std::fill_n(ptr,rows_*cols_,value);
} // 构造rows_*cols_矩阵对象, 初值value
Matrix::Matrix(int rows_, double value): n_rows{rows_},n_cols{rows_},ptr{new double[rows_*rows_]}{
    std::fill_n(ptr,rows_*rows_,value);
}// 构造rows_*rows_方阵对象, 初值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(x.ptr,x.ptr + x.n_rows * x.n_cols,ptr);
}   // 深复制
Matrix::~Matrix(){
    delete[] ptr;
}
void Matrix::set(const double *pvalue, int size){
    if(size != n_rows * n_cols){
        std::cerr << "Error\n";
        std::exit(1);
    }
    for(int i = 0;i < n_rows;i++){
        std::copy(pvalue+i*n_cols,pvalue+(i + 1)*n_cols,ptr+i*n_cols);    
    }
}   // 按行复制pvalue指向的数据,要求size=rows*cols,否则报错退出
void Matrix::clear(){
    std::fill_n(ptr,n_rows*n_cols,0);    
}   // 矩阵对象数据项置0
    
const double& Matrix::at(int i, int j) const{
    if(i > n_cols || j  > n_rows || i<0 || j<0){
        std::cerr << "IndexError: index out of range\n";
        std::exit(1);
    }
    int a = i * n_cols + j;
    return *(ptr + a);
}   // 返回矩阵对象索引(i,j)对应的数据项const引用(越界则报错后退出)
double& Matrix::at(int i, int j){
    if(i > n_cols || j  > n_rows || i<0 || j<0){
        std::cerr << "IndexError: index out of range\n";
        std::exit(1);
    }
    int a = i * n_cols + j;
    return *(ptr + a);
}   // 返回矩阵对象索引(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++){
        std::cout << *(ptr + i*n_cols);
        for(int j = 1;j < n_cols;j++){
            std::cout<< ", " << *(ptr + i*n_cols + j);
        }
        std::cout << '\n';
    }
}   // 按行打印数据 

2.实验测试代码运行结果如下:

屏幕截图 2025-11-21 201736

任务五:

1.源代码:

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

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

(3)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(const auto& con : contacts) {
        if(con.get_name() == name){
            return &con - &contacts[0];
        }
    }
    return -1;
}


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

2.实验测试代码运行结果如下:

屏幕截图 2025-11-21 204620

实验总结:

  (1)深复制是给新对象分配一个新的内存空间,该内存空间的所有属性,数据,内容等,都是复制的复制对象的内容;而浅复制是共有一个地址(内存空间),所以这样会导致两者“绑定”效果;

  (2)巧用c++的标准库,可以简化很多代码,且更便利于实现逻辑功能,是开发更快速,安全;

  (3)对于存储数据*ptr,可以使用容器vector等去存储,这样更代码更加精简,而且对于vector有现成的算法库可以调用,更加快捷,安全,利于理解,提高了开发效率;

  (4)Lambda表达式可以对vector<对象>将对象中的属性进行遍历,比较,这样简化了代码,更利于代码整洁性,而且如果能够掌握这样的编程方式,对于编程速度也能大幅提升。

posted @ 2025-11-21 20:59  Likgon  阅读(6)  评论(0)    收藏  举报