菜鸟的博客

纵有疾风起,人生不言弃。

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

软件设计-实验六

[实验任务一]:向量的原型

用C++完成数学中向量的封装,其中,用指针和动态申请支持向量长度的改变,使用浅克隆和深克隆复制向量类,比较这两种克隆方式的异同。

类图:

复制代码
```mermaid
classDiagram
    Prototype <|-- Vector
    
    class Prototype {
        <<abstract>>
        +clone() Prototype*
        +~Prototype()
    }
    
    class Vector {
        -data int*
        -size int
        +Vector(size int)
        +Vector(other Vector)
        +deepClone() Vector*
        +clone() Prototype*
        +~Vector()
        +set(index int, value int) void
        +get(index int) int
        +print() void
    }
```
复制代码

代码:

复制代码
#include <iostream>
#include <cstring>

// 原型接口类
class Prototype {
public:
    virtual Prototype* clone() const = 0;  // 克隆方法
    virtual ~Prototype() = default;        // 虚析构函数
};

// 向量类,支持原型模式
class Vector : public Prototype {
private:
    int* data;   // 用于存储向量元素的指针
    int size;    // 向量的长度

public:
    // 构造函数
    Vector(int size) : size(size) {
        data = new int[size](); // 动态分配内存并初始化
    }

    // 拷贝构造函数(浅克隆)
    Vector(const Vector& other) : size(other.size), data(other.data) {
        // 直接复制指针,形成浅拷贝
    }

    // 深克隆
    Vector* deepClone() const {
        Vector* newVector = new Vector(size);
        std::memcpy(newVector->data, data, size * sizeof(int)); // 深拷贝数据
        return newVector;
    }

    // 实现浅克隆的 clone 方法
    Prototype* clone() const override {
        return new Vector(*this);  // 调用拷贝构造函数,形成浅拷贝
    }

    // 析构函数
    ~Vector() {
        delete[] data; // 释放动态分配的内存
    }

    // 设置向量元素
    void set(int index, int value) {
        if (index >= 0 && index < size) {
            data[index] = value;
        }
    }

    // 获取向量元素
    int get(int index) const {
        return (index >= 0 && index < size) ? data[index] : -1;
    }

    // 输出向量内容
    void print() const {
        for (int i = 0; i < size; ++i) {
            std::cout << data[i] << " ";
        }
        std::cout << std::endl;
    }
};

int main() {
    // 初始化向量
    Vector vec1(5);
    vec1.set(0, 1);
    vec1.set(1, 2);
    vec1.set(2, 3);

    // 使用浅克隆的 clone 方法
    Prototype* shallowClone = vec1.clone();
    std::cout << "浅克隆向量内容: ";
    static_cast<Vector*>(shallowClone)->print();

    // 使用深克隆方法
    Vector* deepClone = vec1.deepClone();
    std::cout << "深克隆向量内容: ";
    deepClone->print();

    delete shallowClone;  // 释放浅克隆的对象
    delete deepClone;     // 释放深克隆的对象

    return 0;
}
//结果如下:
//浅克隆向量内容:1 2 3 0 0 //深克隆向量内容:1 2 3 0 0
复制代码

 

posted on   hhmzd233  阅读(15)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2023-10-30 读后感:《程序员修炼之道》第三部分 - 提供有价值的工作
点击右上角即可分享
微信分享提示