实验3

实验任务一

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

image

问题1:是

问题2:(1)优点​:外部可查询窗口中是否存在特定按钮,增加灵活性

缺点:可能被误用,破坏封装性

(2)用户是否需要​:若函数是类提供给外部的核心功能,应为 public;若仅用于内部辅助,应为 private。

内部实现细节​:若函数涉及内部状态管理或实现逻辑,应隐藏为 private,避免外部依赖。

​对象状态安全​:若函数可能被误用导致对象状态不一致,应设为 private。

问题3:接口1效率更高

接口2更安全

问题4:正常运行

前者调用构造函数创建临时对象,再通过拷贝构造函数将对象添加到向量中;后者直接在向量内存中构造 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);
}

image

问题1:

v1的构造​:使用vector的构造函数 vector(size_type count, const T& value),创建包含5个值为42的整数向量。
​v2的构造​:使用拷贝构造函数​ vector(const vector& other),将v1的所有元素复制到v2中,因此v2也包含5个值为42的数据

问题2:分别为2,2,3

问题3:能,前者更安全,后者性能更高

问题4:(1)v1.at(0)返回的是非常量引用,允许通过引用r直接修改原始数据。push_back(-1)后,r引用的向量末尾元素即为-1。

(2)​优势​:节省内存,保证原始数据不被意外修改。
​限制​:不能通过常量引用修改数据

问题5:(1)深复制

 (2)int&;const int&;必须提供

 

实验任务三

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

image

问题1:

自赋值问题​:当this == &vi时,先执行delete[] ptr会释放当前对象的内存,随后访问vi.ptr导致未定义行为
​异常安全问题​:如果new int[n]抛出异常,对象将处于无效状态
​内存泄漏风险​:没有检查new是否成功,直接进行拷贝操作

问题2:

(1)将当前对象转换为常量版本,以便调用const版本的at函数;前:vectorInt*,后:const vectorInt*

(2)移除const限定符,返回可修改的引用;前:const int&,后:int&

问题3:

(1)前者是非const版本,后者是const版本

问题4:

可以。第一行:将ptr开始的n个元素都设置为value;第二行:从vi.ptr复制vi.n个元素到ptr;第三行:先复制到临时缓冲区,再交换指针

 

实验任务四

#include "Matrix.hpp"
#include <iostream>
#include <algorithm>
#include <cstdlib>

// 构造函数
Matrix::Matrix(int rows, int cols) 
    : rows_(rows), cols_(cols), data_(new double[rows * cols]) {
    std::fill(data_, data_ + rows * cols, 0.0);
}

Matrix::Matrix(int n) 
    : rows_(n), cols_(n), data_(new double[n * n]) {
    std::fill(data_, data_ + n * n, 0.0);
}

Matrix::Matrix(int rows, int cols, double value) 
    : rows_(rows), cols_(cols), data_(new double[rows * cols]) {
    std::fill(data_, data_ + rows * cols, value);
}

// 拷贝构造函数
Matrix::Matrix(const Matrix& other) 
    : rows_(other.rows_), cols_(other.cols_), data_(new double[other.rows_ * other.cols_]) {
    std::copy(other.data_, other.data_ + rows_ * cols_, data_);
}

// 赋值运算符
Matrix& Matrix::operator=(const Matrix& other) {
    if (this != &other) {
        delete[] data_;
        rows_ = other.rows_;
        cols_ = other.cols_;
        data_ = new double[rows_ * cols_];
        std::copy(other.data_, other.data_ + rows_ * cols_, data_);
    }
    return *this;
}

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

// 成员函数
int Matrix::rows() const {
    return rows_;
}

int Matrix::cols() const {
    return cols_;
}

double& Matrix::at(int i, int j) {
    if (i < 0 || i >= rows_ || j < 0 || j >= cols_) {
        std::cerr << "IndexError: indices out of range\n";
        std::exit(1);
    }
    return data_[i * cols_ + j];
}

const double& Matrix::at(int i, int j) const {
    if (i < 0 || i >= rows_ || j < 0 || j >= cols_) {
        std::cerr << "IndexError: indices out of range\n";
        std::exit(1);
    }
    return data_[i * cols_ + j];
}

void Matrix::set(const double* arr, int size) {
    if (size != rows_ * cols_) {
        std::cerr << "SizeError: input size doesn't match matrix size\n";
        std::exit(1);
    }
    std::copy(arr, arr + size, data_);
}

image

 

 

实验任务五

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

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

// 通讯录类
class ContactBook {
private:
    std::vector<Contact> contacts;
    
    // 方案1:内联实现(推荐)
    int 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;
    }
    
    void sort() {
        std::sort(contacts.begin(), contacts.end(), 
            [](const Contact& a, const Contact& b) {
                return a.get_name() < b.get_name();
            });
    }

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



// 待补足2:void ContactBook::sort();实现
// 按姓名字典序升序排序通讯录
contactBook.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;
}
contact.hpp

 

 

59e4dae11dc87d89d2a6f65cff754bc8

 

posted @ 2025-11-26 00:14  晚夕惋惜婉西  阅读(4)  评论(1)    收藏  举报