面向对象程序设计 实验3

实验任务一

源码以及运行测试截图

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

测试截图

image

问题

问题一:

是组合关系。

buttons_ 声明的是 std::vector<Button>,vector 里存的是 Button 对象本身,不是 Button*。

生命周期也完全由 Window 管:Window 构造的时候在构造函数里放进一个 close 按钮,后面 add_button 再往里加;Window 析构时,成员 buttons_ 跟着析构,vector 又会把里面每个 Button 析构掉。按钮跟窗口同生共死,就是典型的 has-a。

问题二:

① 优点:外部可以先问一下"有没有这个按钮"再决定要不要点,不用每次 click 了才看到 no button。

风险:维护成本变高。

② 我的判断方法:

  1. 用户要用的、属于这个类"能干什么"的功能(add_button、click_button、display)用public。
  2. 只是为了实现别的函数而存在的辅助步骤(has_button)→ private。
  3. 会直接改内部数据、乱调用可能出问题的一定 private,只能通过做过检查的 public 接口去改。

拿不准的先设成 private,以后要开放很容易,公开了再收回来就难了。

问题三:

接口1 返回 const 引用:不拷贝,性能好,调用者只能读取,不能修改内部数据。

接口2:每次调用都要拷贝一份 string(长字符串还要在堆上分配),多了开销,好处是拿到的是独立的一份,原对象怎么变、甚至销毁了都不影响。

一句话:接口 1 快,接口 2 安全。这种一般拿到马上就用的场景,接口1 更合适。

问题四:

① 能正常运行,输出和原来一模一样。

image

区别:push_back(Button("close")) 是先构造一个临时 Button,再把它移进 vector,最后临时对象析构;emplace_back("close") 是把参数直接转发给 Button 的构造函数,在自己的内存上构造,省掉了临时对象那一步。对 Button 这种只有一个 string 的小对象,两种写法差别不大。

② 可以,运行结果一样

std::any_of(first, last, pred):在区间 [first, last) 里,只要有一个元素让 pred 返回 true,就返回 true;一个都没有就返回 false。前两个参数是迭代器,表示查找范围。找到一个就停,不会把后面的也看完。

③ 可以。

std::find_if(first, last, pred):返回区间里第一个让 pred 为 true 的元素的迭代器;找不到就返回 last。所以必须先和 end() 比较再解引用,不然找不到时 it->click() 就越界了。

实验任务二

源码以及运行测试截图

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

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

测试截图

image

问题

问题一:

std::vector<int> v1(5, 42); 是带参数的普通构造。const std::vector<int> v2(v1); 是拷贝构造。

v1、v2 各包含 5 个 42。

问题二:

v1.size() = 2

v2.size() = 2

v1[0].size() = 3

问题三:

能,效果一样,都是把第一个元素改成 -1。

区别在于越界检查:v1[0] 不检查,下标越界是未定义行为。v1.at(0) 会检查。

问题四:

① 能输出 -1。

image

r 是 v1[0] 的引用,不是拷贝出来的新 vector。v1[0] 已经加上了 -1,变成 {1, 2, 3, -1},r.size()-1 就是 3,r[3] 就是 -1。

② 优势:引用不复制整个内层 vector,不额外占内存。

限制:因为是 const,不能通过 r 改内容。

问题五:

① 深拷贝。test1 里改了 v1[0],v2 没变;test2 里 v1[0] 加了 -1,v2[0] 还是 {1, 2, 3},说明没有共享内存。

② v 是 vector<int> 时,v.at(0) 返回 int&;v 是 const vector<int> 时,返回 const int&。

必须提供 const 重载版本。const 对象只能调用 const 成员函数,没有 const 版本的话 const vector 根本调不了 at。

实验任务三

源码以及运行测试截图

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

测试截图

输入 n = 6

image

问题

问题一:

改成版本2 以后:

image

测试3 有异常:x.assign(x) 之后 x 的数据没了,全变成了 0。测试1、测试2 正常,因为它们不是自己赋值给自己。

版本2 的问题:

  1. 没有自赋值检查。x.assign(x) 时 this 和 &vi 是同一个对象,第一句把自己的数据释放了;接着 pdata_ = new int[n_],这时候 vi.pdata_ 其实也就是这块新内存,后面的循环等于把一块未初始化的内存抄给它自己。原来的 42 已经找不回来了。

问题二:

① 在非 const 的 at 里,this 的类型是 vectorInt*,转换后变成 const vectorInt*。

目的是让后面的 ->at(index) 调到 const 版本的 at。

② const 版本 at 返回的是 const int&,const_cast<int&> 把 const 去掉,变成 int&,跟非 const 版本的返回类型对上,这样外面才能 x.at(i) = … 去修改。

问题三:

it1:v1 是普通对象,两个版本都能调,编译器优先精确匹配的非 const 版本 int* begin(),it1 是 int*。

it2:v2 是 const 对象,只能调 const 版本 const int* begin() const,it2 是 const int*。

非 const 版本用在需要改元素的地方,const 版本用在只读的地方。

问题四:

可以,改完运行结果和原来一样。

image

1: std::fill_n(pdata_, n_, value);:从 pdata_ 开始,把连续 n_ 个元素都赋值为 value。

2: std::copy_n(vi.pdata_, vi.n_, pdata_);:从 vi.pdata_ 开始复制 vi.n_ 个元素到 pdata_ 开始的位置,也就是拷贝构造里深拷贝数据那一步。

3: std::copy_n(vi.pdata_, vi.n_, ptr);:同样是复制 vi.n_ 个元素,目标是新申请的 ptr。

实验任务四

源码以及运行测试截图

matrix.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[n_rows_ * 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';
}

测试截图

输入 2 5

image

问题

问题一:set() 的潜在风险

有风险。把 x 改成只有 5 个元素,输入 2 3:

image

m1 第二行最后一个数、m2 最后一个数变成了莫名其妙的值。

原因:set 里的检查是 size != n_rows_ * n_cols_,可是 size 本来就是调用者按 n*m 算好传进来的,跟矩阵大小肯定相等,这个检查没用。set 根本不知道 pvalue 指的数组实际有多大,copy_n 就从 x 后面接着读,属于越界读、未定义行为。最麻烦的是程序没崩,悄悄给了个错的结果,比直接崩更难发现。

问题二:怎么优化 set()

让数据自己带着长度进来,

void Matrix::set(const std::vector<double> &values) {
    if(values.size() != static_cast<std::size_t>(n_rows_ * n_cols_))
        throw std::invalid_argument("数据错误");

    std::copy(values.begin(), values.end(), pdata_);
}

测试代码里 x 改成 std::vector<double> x{1, 2, 3, 4, 5};,调用改成 m1.set(x);,main 里给 test1 套了一层 try-catch。同样输入 2 3:

image

实验任务五

源码以及运行测试截图

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 {
    auto it = std::find_if(contacts_.begin(), contacts_.end(),
        [&](const Contact &c) { return c.get_name() == name; });

    if(it == contacts_.end())
        return -1;
    return static_cast<int>(it - contacts_.begin());
}



// 待补足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();
}

测试截图

image