[实验任务一]:向量的原型
用C++完成数学中向量的封装,其中,用指针和动态申请支持向量长度的改变,使用浅克隆和深克隆复制向量类,比较这两种克隆方式的异同。
#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; }
标签:vector,const,int,模式,len,Vector,原型,C++,向量 From: https://www.cnblogs.com/rongzhang/p/16773880.html