oop实验三

实验任务一

源代码:

#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();
}
task1.cpp
#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";
}
button.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;
}
window.hpp

运行结果:

屏幕截图 2025-11-19 083757

问题:

Q1:是的,我觉得是组合关系,因为window类有一个成员变量是std:vector<button>buttons,就是每个window对象都有button对象。窗口创建时按钮被创建,窗口关闭时它们被销毁,这样的类型就是组合关系。

Q2:

  (1):优点是外面的人能直接调用这个函数来查询窗口有没有某个按钮 ,可能会更方便。缺点是暴露给外界后如果以后自己想修改has_button的实现方式会影响到别人使用,而且且也不符合封装性。

  (2):如果是public,那就是给类的外部用户用的,函数的功能是用户完成任务需要的。如果是private,那就是给自己用的,用户对象不需要使用与知道。

Q3:接口一,返回的时label本身,没有副本,花费时间少速度快;安全性上,如果按钮被销毁了,那就用不了了。接口二,性能上就是把内部label字符串复制一份,这样如果字符串很长时复制就会浪费时间;安全性上,作为完整的副本很安全,就算按钮被销毁也能用。

Q4:能够正常运行。我的理解是push_back时构造一个临时对象然后把这个临时对象移动拷贝到vector末尾。而emplace_back是直接吧label这个参数传给vector。

 

实验任务二

 源代码:

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

运行结果:

屏幕截图 2025-11-19 153612

问题:

Q1:第一行代码是创建了一个叫v1的vector,里面有5个数字,每个数字都是42。第二行代码是用v1来创建一个新的vector叫v2,v2里面的内容和v1完全一样。v1和v2都包含5个值为42的数据项。

Q2:v1.size()是2,因为v1里面有2个小vector。v2.size()也是2,因为v2是v1的拷贝,所以也有2个小vector。v1[0].size也是3,因为v1的第一个小vector里面有3个数字分别是1,2,3。

Q3:可以效果都是v1的第一个数改成-1。区别是at(0)会检查0这个位置是否存在,如果不存在就会报错。而[0]不会检查,如果位置不存在可能程序崩溃。

Q4:

  (1):可以输出-1,因为r是v1第一个小vector的引用,v1.at(0).push_back(-1)在第一个小vector的最后面加了一个-1,所以r.at(r.size()-1)就是取最后一个数,也就是-1。

  (2):好处是节省内存,因为它不会把整个vector再复制一份,而是直接使用原来的vector。限制是不能通过这个const&来修改vector里面的内容。

Q5:

  (1):从运行结果来看,修改v1不会影响v2,说明vector的复制构造函数做的是深复制。就是说v1和v2各有自己独立的内存空间。

  (2):当v是普通的vector<int>时,v.at(0)返回的是int&,可以修改这个数。当v是const vector<int>时,v.at(0)返回的是const int&,只能读取不能修改。

       at()必须提供const版本的重载,因为如果只有非const版本,那么在const对象上就用不了at()了。有了const版本,就既可以在普通vector上使用,也能在const vector上使用。

 

实验任务三

源代码:

#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;
}
vectorInt.hpp
#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';
}
task3.cpp

运行结果:

屏幕截图 2025-11-19 161043

问题:

Q1:版本2x.assign(x),这样会先把自己的ptr删掉,然后又去用已经被删掉的ptr来复制数据,程序会崩溃。而原版本是准备好新的数据,没问题后再删除旧的,这样更稳妥。

Q2:

  (1):这句话的作用是转换指针类型。转换前this是普通的vectorInt指针,转换后变成了const vectorInt指针。目的是

  (2):这句话的作用是把不能修改的引用转化为可以修改的引用。转化前从const版本at得到的是const int&(不能修改的引用),转化后变成int&(可以修改的引用)。目的是由于最终要返回的是可以修改的引用,所以要把const去掉。

Q3:v.begin是调用非const版本,因为v1是普通对象。v2.begin是调用const版本,因为v2是const对象。非const版本是当你想修改vector里面的数据时用这个,const版本是当你只想读取数据不想修改时用这个。

Q4:第一行代码是把value这个值复制n份,从ptr开始的位置连续放好。这样代替了原来要写一个for循环来逐个赋值。第二行代码是类似于整段复制,把vi.ptr开始的vi.n个数据,整个复制到ptr那里,代替了原来要写循环一个一个元素的拷贝。第三行代码也是整段复制,把从vi.ptr开始的vi.n个数据整个复制到ptr_tmp那里。

 

实验任务四

源代码:

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

Matrix::Matrix(int rows_, int cols_, double value) {
    n_rows = rows_;
    n_cols = cols_;
    if (rows_ <= 0 || cols_ <= 0) {
        std::cout << "Error: Invalid matrix dimensions" << std::endl;
        exit(1);
    }
    ptr = new double[n_rows * n_cols];
    for (int i = 0; i < n_rows * n_cols; i++) {
        ptr[i] = value;
    }
}

Matrix::Matrix(int rows_, double value) {
    n_rows = rows_;
    n_cols = rows_;
    if (rows_ <= 0) {
        std::cout << "Error: Invalid matrix dimension" << std::endl;
        exit(1);
    }
    ptr = new double[n_rows * n_cols];
    for (int i = 0; i < n_rows * n_cols; i++) {
        ptr[i] = value;
    }
}

Matrix::Matrix(const Matrix &x) {
    n_rows = x.n_rows;
    n_cols = x.n_cols;
    ptr = new double[n_rows * n_cols];
    for (int i = 0; i < n_rows * n_cols; i++) {
        ptr[i] = x.ptr[i];
    }
}

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

void Matrix::set(const double *pvalue, int size) {
    if (size != n_rows * n_cols) {
        std::cout << "Error: Size mismatch in set function" << std::endl;
        exit(1);
    }
    
    for (int i = 0; i < size; i++) {
        ptr[i] = pvalue[i];
    }
}

void Matrix::clear() {
    for (int i = 0; i < n_rows * n_cols; i++) {
        ptr[i] = 0;
    }
}

const double& Matrix::at(int i, int j) const {
    if (i < 0 || i >= n_rows) {
        std::cout << "Error: Row index out of bounds" << std::endl;
        exit(1);
    }
    if (j < 0 || j >= n_cols) {
        std::cout << "Error: Column index out of bounds" << std::endl;
        exit(1);
    }
    
    return ptr[i * n_cols + j];
}

double& Matrix::at(int i, int j) {
    if (i < 0 || i >= n_rows) {
        std::cout << "Error: Row index out of bounds" << std::endl;
        exit(1);
    }
    if (j < 0 || j >= n_cols) {
        std::cout << "Error: Column index out of bounds" << std::endl;
        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 << std::endl;
    }
}
matrix.cpp
#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.hpp
#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';
}
task4.cpp

运行结果:

 屏幕截图 2025-11-22 114943

 

 

实验任务五:

源代码:

#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();
}
task5.cpp
#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
# 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 (int i = 0; i < contacts.size(); i++) {
        if (contacts[i].get_name() == name) {
            return i; 
        }
    }
    return -1; 
}

// 待补足2:void ContactBook::sort();实现
// 按姓名字典序升序排序通讯录
void ContactBook::sort() {
    int n = contacts.size();
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (contacts[j].get_name() > contacts[j + 1].get_name()) {
                Contact temp = contacts[j];
                contacts[j] = contacts[j + 1];
                contacts[j + 1] = temp;
            }
        }
    }
}
contactBook.hpp

运行结果:

屏幕截图 2025-11-22 134012

 

posted @ 2025-11-22 13:43  周心岚  阅读(9)  评论(1)    收藏  举报