实验3

类和对象_基础编程2

任务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";
}
  • 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;
}
  • 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;
}
  • 运行截图
    屏幕截图 2026-11-26 224804

  • 问题1
    是组合关系。 理由:
    buttons_ 声明为 std::vector

  • 问题2
    ① 改为公有的优点与风险:
    优点:外部可直接查询某按钮是否存在,便于调用方做前置判断,减少"盲点"异常输出。
    风险:暴露内部实现细节,增大接口面;外部可能依赖该实现,日后若改用 map 等结构会破坏兼容性;且它只是内部辅助逻辑,公有化易诱导外部围绕它写耦合代码。
    ② public/private 决策角度:
    1.用户是否需要:外部调用者是否真的需要该功能;
    2.是否仅为内部实现细节:辅助函数、实现步骤应私有;
    3.是否易破坏对象状态:能修改内部不变式、暴露内部结构的应私有;
    4.最小接口原则:只暴露必要接口,降低耦合与维护成本。

  • 问题3
    接口1 const std::string&:返回内部成员的引用,无拷贝,性能好;但返回引用意味着暴露内部数据,调用方若保存该引用,对象销毁后成悬空引用;用 const 限定保证只读,安全性靠 const 约束。
    接口2 std::string:返回副本,有拷贝开销;但调用方拿到独立对象,无悬空风险,安全性更高。
    精炼陈述:接口1 零拷贝、高性能,但需注意生命周期且依赖 const 保证只读;接口2 安全独立但有拷贝成本。本场景 label 只读且生命周期由 Window 保证,接口1 更合适。

  • 问题4
    ①push_back vs emplace_back:
    push_back(Button(xxx)) 先构造临时 Button 对象再移动/拷贝进 vector;emplace_back(xxx) 直接在 vector 内存中就地构造,省去临时对象与一次移动/拷贝。
    改成 emplace_back(xxx) 程序正常运行,行为一致,但效率更高(避免临时对象)。注意 emplace_back 转发参数给构造函数,若参数类型不匹配可能引发隐式转换问题。
    ② std::any_of:
    功能:对区间 [first, last) 内元素依次应用谓词,判断是否存在满足条件的元素。
    参数:起始迭代器、终止迭代器、一元谓词(返回 bool)。
    返回值:bool,存在任一满足则 true,否则 false。
    该写法可以,与手写循环语义等价,更简洁。
    ③ std::find_if:
    功能:在区间 [first, last) 中查找第一个满足谓词的元素。
    参数:起始迭代器、终止迭代器、一元谓词。
    返回值:指向第一个满足条件元素的迭代器;找不到返回 last。
    该写法可以,it != buttons_.end() 判断找到,it->click() 调用,逻辑与手写循环等价。

任务2

  • 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);
}
  • 运行截图

屏幕截图 2026-11-26 225533

  • 问题1
    std::vector v1(5, 42);:指定大小+初值构造,v1 含 5 个值为 42 的元素。
    const std::vector v2(v1);:拷贝构造,v2 也含 5 个值为 42 的元素,且与 v1 独立。
  • 问题2
    v1.size() = 2(两个内层 vector)
    v2.size() = 2
    v1[0].size() = 3({1,2,3})
  • 问题3
    v1.at(0) = -1; 能实现同等效果。
    区别:operator[] 不做越界检查,越界是未定义行为;at() 做越界检查,越界抛 std::out_of_range 异常。at 更安全但有轻微检查开销。
  • 问题4
    ① 能。v1[0].push_back(-1) 后 v1[0] 为 {1,2,3,-1};const std::vector &r = v1[0] 绑定到该内层 vector,r[r.size()-1] 即 r[3] 为 -1。能输出 -1。
    ② const & 接收返回值的优势与限制:
    优势:避免拷贝,零开销;引用直接指向原对象,内存使用最省。
    限制:只读;且是别名,原对象销毁或底层 reallocation 后引用可能失效,需保证原对象生命周期
  • 问题5
    ① vector 复制构造函数实现的是深拷贝:修改 v1 后 v2 不受影响,说明两对象各自拥有独立内存。
    ② at() 返回值类型:
    v 为 vector 时,v.at(0) 返回 int&(可修改);
    v 为 const vector 时,v.at(0) 返回 const int&(只读)。
    据此推断:必须提供带 const 修饰的重载版本,否则 const 对象调用 at() 无法编译(或返回非 const 引用破坏 const 正确性)。这正是 const 重载存在的意义。

任务3

  • 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';
}
  • vectorlnt.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_;
}
  • 运行截图

屏幕截图 2026-11-26 230048

  • 问题1
    自赋值危险:先 delete[] pdata_,若 vi 就是 *this,则 vi.pdata_ 已被释放,随后 vi.pdata_[i] 读取已释放内存(use-after-free),且 n_ 已被改。test3 中 x.assign(x) 会触发此问题,输出异常/崩溃。
    异常不安全:先释放旧内存再 new,若 new 抛 bad_alloc,对象处于 pdata_ 悬空、n_ 已改的不一致状态。
    无自赋值检查(缺少 if(this == &vi) return *this;)。
    顺序缺陷:先删后建,若中途失败资源全失;安全版本是"先 new 新块→拷贝→再 delete 旧块→更新成员"。
  • 问题2
    ① static_cast<const vectorInt>(this):
    转换前 this 类型为 vectorInt
    (非 const 指针),转换后为 const vectorInt*。
    目的:把非 const 的 this 转为 const 指针,以便调用 const 版本的 at(),复用其越界检查逻辑。
    ② const_cast<int&>:
    转换前返回类型 const int&,转换后为 int&。
    目的:去除 const 限定,把 const 版 at() 返回的只读引用转成可写引用,供非 const 版本返回。安全性由"原对象本身非 const、且调用方通过非 const 对象访问"来保证。
  • 问题3
    ①v1 非 const → 调用非 const 版本 int* begin(),it1 为 int,可读写。
    v2 const → 调用 const 版本 const int
    begin(),it2 为 const int*,只读。
    场景:非 const 版本用于需要修改元素的遍历;const 版本用于只读遍历/const 对象,保证 const 正确性。
  • 问题4
    可以,三行更新代码功能:
    更新1 std::fill_n(pdata_, n_, value):把 [pdata_, pdata_+n_) 区间 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 数据拷到新分配的 ptr 块,等价原循环,保持"先建新块再删旧块"的安全顺序。

任务4

  • matrix.cpp源代码
点击查看代码

![image](https://img2024.cnblogs.com/blog/3861770/202611/3861770-20261126231406086-1282488997.png)

  • 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_;    // 数据区
};
  • 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';
}
  • 运行截图

image

  • 问题
    是的,set(const double pvalue, int size) 的设计确实暴露了潜在风险。 当测试模块的数组 x 被改为不足 nm 个元素(例如 double x[1000] = {8,8,8,8};),运行输入 2 3 或 2 5 时,set() 内部的 std::copy_n(pvalue, size, pdata_) 会越界读取 x 数组之外的内存,程序可能输出垃圾值、崩溃,或产生不可预测的行为,而 set() 本身完全无法察觉。

若输入 2 5,m1 需要 10 个元素,越界读取更严重。set() 的 size 参数只校验了“声称的长度是否等于矩阵元素数”,完全没有校验“声称的长度是否超出了 pvalue 实际可读的范围”。

  • 改良方案
    在测试模块中,用 std::size(x)(C++17)获取数组真实长度,与 n*m 比较后再调用 set();
    或在 set() 文档注释中明确警告:“pvalue 必须指向至少 size 个可读 double,调用方负责保证”。
    但这些都是“把责任推给调用方”的权宜之计,并未从根本上让接口更安全。

任务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.cpp源代码
点击查看代码
# 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 (size_t i = 0; i < contacts_.size(); ++i) {
        if (contacts_[i].get_name() == name)   // std::string 的 == 区分大小写
            return static_cast<int>(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();
}
  • 运行截图

屏幕截图 2026-11-26 232235

posted @ 2026-11-26 23:23  徐玮伦  阅读(0)  评论(0)    收藏  举报