软件设计Tutorial 6_原型模式

发布时间 2023-11-14 14:25:16作者: 花伤错零

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

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

实验要求:

1.  画出对应的类图;

 

 

2.  提交源代码(用C++完成);

 

#include <iostream>

#include <cstring>

 

class Vector {

private:

    int size;

    double *data;

 

public:

    // 构造函数

    Vector(int size) {

        this->size = size;

        data = new double[size];

    }

 

    // 析构函数

    ~Vector() {

        delete[] data;

    }

 

    // 复制构造函数

    Vector(const Vector& other, bool deep_clone = true) {

        size = other.size;

        data = new double[size];

        if (deep_clone) {  

            std::memcpy(data, other.data, size * sizeof(double));   //深克隆

        } else {

            data = other.data; // 浅克隆,共享底层数组

        }

    }

 

    // 重设向量大小

    void resize(int new_size) {

        double *new_data = new double[new_size];

        int min_size = (new_size < size) ? new_size : size;

        std::memcpy(new_data, data, min_size * sizeof(double));

        delete[] data;

        data = new_data;

        size = new_size;

    }

 

    // 获取向量大小

    int getSize() const {

        return size;

    }

 

    // 获取向量元素

    double get(int index) const {

        if (index >= 0 && index < size) {

            return data[index];

        } else {

            std::cerr << "Index out of bounds." << std::endl;

            return 0.0; // 默认返回值

        }

    }

 

    // 设置向量元素

    void set(int index, double value) {

        if (index >= 0 && index < size) {

            data[index] = value;

        } else {

            std::cerr << "Index out of bounds." << std::endl;

        }

    }

};

 

int main() {

    // 创建一个向量对象

    Vector vector1(5);

    vector1.set(0, 1.0);

    vector1.set(1, 2.0);

    vector1.set(2, 3.0);

 

    // 浅克隆

    Vector vector2(vector1, false);

    vector2.set(0, 10.0);

    std::cout << "Vector1[0]: " << vector1.get(0) << std::endl;

 

    // 深克隆

    Vector vector3(vector1);

    vector3.set(0, 20.0);

    std::cout << "Vector1[0]: " << vector1.get(0) << std::endl;

 

    return 0;

}