软件设计-实验六
[实验任务一]:向量的原型
用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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2023-10-30 读后感:《程序员修炼之道》第三部分 - 提供有价值的工作