实验3

四、实验结论

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

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

1

问题1:是。buttons_的声明方式:std::vector<Button> buttons_,是Button对象本身,不是指针。对象跟着Window对象一起构造、析构,生命周期由Windows管。这种整体和部分生命周期绑定在一起的是组合。

问题2:

① 优点:外面也能查这个按钮在不在,调试、写测试时不用再自己写一遍循环。风险:暴露了内部细节,类公共对外的面变大了,容易有人绕开add_button,自己去拼装按钮,破坏“名字不重复”这个约定。

② 一是用户是否需要,只给类内部用的为private;二是它是否用来单纯实现细节,比has_button这种为了判重、找位置、算中间结果的函数,是内部内容,不该露出去;三是它是否会破坏对象状态,如果能直接改内部数据则 private。

问题3:接口1 返回 const 引用,接口2 返回值,差别在“给不给副本”。

接口1:返回const引用,不复制,直接把内部string的只读别名交出去,省掉一次拷贝,性能好。同时,加了const之后不能改变label_,内部数据不会被改掉。代价是这个引用跟对象绑在一起,按钮被删了或vector扩容重新分配了,手里的引用就悬空了。

接口2:返回值,每调用一次就复制一份,副本跟原对象无关,改动副本不影响按钮,也不会悬空,较为安全;但复制string成本相较接口1较大。

问题4:

① 正常运行。区别:push_back(Button(label))是先在栈上造一个临时 Button对象,再把它拷贝到vector里,最后析构;emplace_back(label)是把label直接移动到 vector 里,原地构造Button,少了一次临时对象的构造和析构。

② 可以。std::any_of(first, last, pred)的功能是在 [first, last) 这个区间里挨个试pred,只要有任意一个元素让pred返回true就立刻返回true,全都不满足返回false。first和last是范围,返回bool类型。

③ 可以。std::find_if(first, last, pred)的功能是返回第一个让pred为true的元素,一个都没有就返回last。first和last是范围,返回迭代器。

问题5:不会。改成std::map<std::string, Button>后,display()输出顺序就变成字典序close、add、modify、remove。我觉得不太能接受,按钮位置突然改变对用户不太友好。

2.实验任务2

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

2

问题1:v1是填充构造,开5个元素、每个填42;v2是拷贝构造,复制v1一份。v1、v2各有5个值为42的数据项。

问题2:v1.size()是2,v2.size()是2,v1[0].size()是3。

问题3:能。区别:operator[]不检查下标,越界可能读到别人的内存,而at()会检查,越界抛out_of_range。

问题4:

① 能。r 是v1[0]的引用,跟v1[0]是同一块,push_back(-1)改是它,r.size()-1正好是最后一位。

②优势:const&接收不复制数据,既省内存也省时间。限制:只能读,不能push_back、不能r[0] = x;引用要一直有效,v1 销毁、或者 v1[0] 重新分配之后就无效了。

问题5:

① 深拷贝。改v1[0]后v2没变,说明两者各有自己的数据区域。浅拷贝会共用同一块内存,改一个另一个跟着变。

② 不是const时at()返回int&,是const时返回const int&,必须提供 const 重载。只有非const的话,const对象调用不了。

3.实验任务3

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

3

4

问题1:有异常。代码差异:版本1是先new新的、把数据拷贝过去、再delete旧的、最后改n_和pdata_,版本2是先delete、再改n_、然后new。

安全隐患和缺陷:一是test3就是x.assign(x),版本2先把pdata_释放掉,成了悬空指针,接着循环从vi.pdata_拷数据,但vi就是自己,在读已经释放的内存,数据全错了;二是异常不安全。先释放再申请,new如果抛bad_alloc,对象就停在pdata_悬空且n_已改的状态,析构再delete[]一次悬空指针就进行了二次释放。

问题2:

①作用是把this从vectorInt*转成const vectorInt*,让这次调用去匹配const版的at(),目的是把非const版调const版。

② 作用是const版返回的是const int&,去掉const变成int&,非const版对外才能被赋值,目的是在非const对象上调用被赋值。

问题3:

① v1是非const,调用int* begin(),v2是const,调用const int*。编译器靠this参数类型选重载,非const对象的this是vectorInt*,优先选非const版;const对象的this是const vectorInt*,只能匹配const版。要改元素用非const版,只读用const版。

②我的理解是迭代器的本质是指向元素的位置。

问题4:可以。fill_n(pdata_, n_, value)把从pdata_起连续n_个元素都填成value。copy_n(vi.pdata_, vi.n_, pdata_)把从vi.pdata_拷vi.n_个元素,放到pdata_。copy_n(vi.pdata_, vi.n_, ptr)把vi的数据拷到新申请的ptr上。

4.实验任务4

martix.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)  : n_rows_{x.n_rows_}, n_cols_{x.n_cols_},pdata_{new double[x.n_rows_ * x.n_cols_]} {
    std::copy_n(x.pdata_, n_rows_ * n_cols_, pdata_);
}

// 待实现:释放指针指向的内存资源
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) {
        std::cout << pdata_[i * n_cols_];
        for(int j = 1; 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.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';
}

5

问题:是。set()只能查size是否等于rows*cols,却不能知道pvalue指的数组实际长度。优化:参数换成vector、array,用size()校验。

5.实验任务5

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

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(); // 按姓名字典序升序排序通讯录

private:
    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 < static_cast<int>(contacts_.size()); ++i)
        if(contacts_[i].get_name() == name)
            return i;
 
    return -1;
}

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

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

6

拓展思考:

修改联系人功能:加一个update(name, phone),内部先用index找到位置再改 phone,公有接口不动,原来的add/remove/find/display都不受影响。

数据有效性校验:手机号位数对不对、是否全是数字,在add里先查一遍,不合法就提示。

异常处理:改成返回bool。

数据持久化存储:加load(),把contacts写成文本,补一个序列化函数。

模糊检索:加个group字段,查找从==改成std::string::find做子串匹配。

五、实验总结

这次实验做完之后对类的理解比上个实验多了很多。任务1的Window和Button加深了我对组合的理解,成员直接写成std::vector<Button>,按钮的生命周期跟着窗口走,不用自己new也不用自己delete。任务2和任务3对深拷贝有了更深的理解。写vectorInt时明白拷贝构造里不重新申请一块内存,两个对象就会共用同一块数据。任务3assign的自赋值问题让我明白,先delete再new在x.assign(x)的情况下会去读刚释放的内存,正确做法是先把新块备好、拷贝完再切换。const决定了这个对象能调哪些成员函数,也决定了at()、begin()要写两套。这次实验用std::any_of替换has_button、用find_if替换click_button、用fill_n和copy_n替换手写循环,代码更简洁易读。

posted @ 2026-11-26 20:34  hyoseon  阅读(9)  评论(0)    收藏  举报