C++学习(12)
1 //设计一个double类型的数组Array 2 //1.可定义下界下标和上届上标 3 //2.可对下标越界进行检查 4 //3.可重置数组大小 5 //4.可知道数组的长度 6 //5.数组类的对象可以使用赋值运算符=和下标运算符[] 7 8 #include<iostream.h> 9 #include<stdlib.h> 10 class Array{ 11 private: 12 int size; 13 int low; 14 int up; 15 double *arr; 16 public: 17 Array(int sz=100); 18 Array(int low,int up); 19 Array(const Array &arr); 20 ~Array(); 21 22 void operator=(const Array &arr); 23 double &operator[](int ndx)const; 24 void Resize(int sz); 25 void Resize(int ll,int hh); 26 int ArraySize()const; 27 }; 28 29 Array::Array(int sz){ 30 if(sz<=0){ 31 exit(0); 32 } 33 34 low=0; 35 up=sz-1; 36 size=sz; 37 arr=new double[size]; 38 } 39 40 Array::Array(int low,int up){ 41 this->low=low; 42 this->up=up; 43 size=up-low+1; 44 arr=new double[size]; 45 } 46 47 Array::Array(const Array &arr){ 48 int n=arr.size; 49 size=n; 50 this->arr=new double[size]; 51 52 double *sourcePtr=arr.arr; 53 double *destPtr=this->arr; 54 while(n--){ 55 *destPtr++=*sourcePtr++; 56 } 57 } 58 59 Array::~Array(){ 60 delete []this->arr; 61 } 62 63 void Array::operator=(const Array &arr){ 64 if(&arr==(this)){//如果是自己等于自己,那么返回空 65 return; 66 } 67 68 int n=arr.size; 69 size=n; 70 this->arr=new double[size]; 71 72 double *sourcePtr=arr.arr; 73 double *destPtr=this->arr; 74 while(n--){ 75 *destPtr++=*sourcePtr++; 76 } 77 } 78 79 //1.double &Array::operator[] 重载运算符返回double &这个是引用类型。 80 //不加&表示返回对象, 81 //2.加了&之后,就可以作为左值进行赋值操作了。 82 //比如对A重载[]操作,加&之后,可以实现 A[i]=v;这样的操作目的。 83 double &Array::operator[](int ndx)const{ 84 if((ndx<low) || (ndx>size-1) ){ 85 cout<<"数组下标越界"<<endl; 86 exit(0); 87 } 88 return this->arr[ndx-low]; 89 } 90 91 92 void Array::Resize(int sz){ 93 if(sz<0){ 94 exit(0); 95 } 96 if(sz==this->size){ 97 return; 98 } 99 100 double *newArray=new double[size]; 101 int n=(sz<=size)?sz:size; 102 double *sourcePtr=arr; 103 double *destPtr=newArray; 104 while(n--){ 105 *destPtr++ = *sourcePtr++; 106 } 107 delete []this->arr; 108 109 this->arr=newArray; 110 this->size=sz; 111 this->low=0; 112 this->up=size-1; 113 } 114 115 116 void Array::Resize(int ll,int hh){ 117 int sz=hh-ll+1; 118 double *newArray=new double[sz]; 119 120 int n=(sz<=this->size)?sz:size; 121 double *sourcePtr=this->arr; 122 double *destPtr=newArray; 123 124 while(n--){ 125 *destPtr++=*sourcePtr++; 126 } 127 128 delete []this->arr; 129 this->arr=newArray; 130 this->size=sz; 131 this->low=ll; 132 this->up=hh; 133 } 134 135 int Array::ArraySize()const{ 136 return this->size; 137 } 138 139 int main(){ 140 Array a(-5,5); 141 cout<<"ArraySize="<<a.ArraySize()<<endl; 142 for(int i=-5;i<5;i++){ 143 a[i]=i; 144 } 145 146 a.Resize(30); 147 a[21]=21; 148 cout<<"ArraySize="<<a.ArraySize()<<endl; 149 150 return 0; 151 }
posted on 2018-06-29 19:11 孙悟空son_ku_kong 阅读(132) 评论(0) 编辑 收藏 举报