2.1

用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 @ 2024-10-23 19:37  徐星凯  阅读(30)  评论(0)    收藏  举报