今天我完成了一道软件设计的实验题,运用c++实现一些功能;
(1)对应的类图:
(2)源代码;
1.浅克隆运行代码:
#include <iostream> using namespace std; //向量类 class Vector{ private: int *p; int len; public: Vector(int len); Vector(const Vector &vector); //拷贝构造函数 ~Vector(); int operator[](int i) const { return p[i]; } int &operator[](int i){ return p[i]; } int length() const { return len; } }; Vector::Vector(int len): len(len){ p = (int*)calloc( len, sizeof(int) ); } //拷贝构造函数 Vector::Vector(const Vector &vector){ this->len = vector.len; this->p = vector.p; } Vector::~Vector(){ free(p); } //打印 void display(const Vector &vector){ int len = vector.length(); for(int i=0; i<len; i++){ if(i == len-1){ cout<<vector[i]<<endl; }else{ cout<<vector[i]<<", "; } } } int main(){ Vector v1(10); for(int i=0; i<10; i++){ v1[i] = i; } Vector v2 = v1; v2[6] = 55; v2[2] = 20; cout<<"浅克隆:"<<endl; cout<<"更改copyVector后vector的数据:"<<endl; display(v1); cout<<"更改copyVector后copyVector的数据:"<<endl; display(v2); return 0; }
2.深克隆运行代码:
#include <iostream> using namespace std; //向量类 class Vector{ private: int *p; int len; public: Vector(int len); Vector(const Vector &vector); //拷贝构造函数 ~Vector(); int operator[](int i) const { return p[i]; } int &operator[](int i){ return p[i]; } int length() const { return len; } }; Vector::Vector(int len): len(len){ p = (int*)calloc( len, sizeof(int) ); } //拷贝构造函数 Vector::Vector(const Vector &vector){ this->len = vector.len; this->p = (int*)calloc( this->len, sizeof(int) ); memcpy( this->p, vector.p, len * sizeof(int) ); } Vector::~Vector(){ free(p); } //打印 void display(const Vector &vector){ int len = vector.length(); for(int i=0; i<len; i++){ if(i == len-1){ cout<<vector[i]<<endl; }else{ cout<<vector[i]<<", "; } } } int main(){ Vector v1(10); for(int i=0; i<10; i++){ v1[i] = i; } Vector v2 = v1; v2[6] = 55; v2[2] = 20; cout<<"深克隆:"<<endl; cout<<"更改copyVector后vector的数据:"<<endl; display(v1); cout<<"更改copyVector后copyVector的数据:"<<endl; display(v2); return 0; }
标签:总结,vector,const,int,每日,len,Vector,return From: https://www.cnblogs.com/tianminggeng/p/17804629.html