#include<iostream> using namespace std; class Array { public: Array()//无参构造函数 { this->len = 0; this->space = NULL; cout<<"Array()"<<endl; } Array(int len)//有参构造函数 { if(len<=0) { this->len = 0; this->space = NULL; } else { this->len = len; this->space = new int[len]; cout<<"创建了一个长度为"<<len<<"的数组"<<endl; } } Array(const Array &another)//拷贝构造函数,把另一个数组拷贝过来 { if(another.len>=0) { this->len = another.len; //执行深拷贝 //先给新对象在堆中创建一定长度的数组 this->space = new int[this->len]; //把原对象的值赋给新对象 for(int i =0;i<this->len;i++) { this->space[i] = another.space[i]; } cout<<"调用了默认拷贝构造函数"<<endl; } } ~Array()//析构函数 { if(this->space != NULL) { delete[] this->space;//要先释放this->space指向的空间 this->space = NULL;//再干掉space这个指针 len = 0; } cout<<"~Array()"<<endl; } //重载等号操作符 void operator=(const Array &another) { if(another.len>=0) { this->len = another.len; this->space = new int[this->len]; for(int i =0;i<this->len;i++) { this->space[i] = another.space[i]; } cout<<"调用了等号操作符的复制"<<endl; } } //根据索引赋值 void set(int index,int value){ if(this->space!=NULL&&index<len&&index>=0) { this->space[index] = value; } } //打印特定索引的值 int index(int index){ if(this->space!=NULL&&index<len&&index>=0) { return this->space[index]; } } //返回数组长度 int length(){ return this->len; } //打印列表值,有重载的cout void values(){ for(int i = 0;i<this->len;i++) { cout<<this->space[i]<<"\t"; } cout<<endl; } //数组反转 void reverse() { int temp; for(int i = this->len-1,j=0; j<=i;i--,j++) { temp = this->space[j]; this->space[j] = this->space[i]; this->space[i] = temp; } cout<<"调用了reverse()"<<endl; } //重载==运算符,!=是类似的 bool operator==(Array &another) { cout<<"用==操作符判断数组是否相等"<<endl; if(this->len != another.len) { return false; } else { for(int i = 0;i<this->len;i++) { if(this->space[i] != another.space[i]) { return false; } } } return true; } //重载!= bool operator!=(Array &another) { cout<<"调用了!="<<endl; if(*this == another) { return false; } else { return true; } } //声明友元函数 friend ostream& operator<<(ostream& os,Array& a); private: int len; int* space; }; //重载的左移运算符,直观来讲就是可以使用cout打印数组 ostream& operator<<(ostream& os,Array& a)//记得返回ostream对象,不然会报段错误 { for(int i = 0;i<a.len;i++) { cout<<a.space[i]<<"\t"; } return os; } int main() { //先随便定义一个要被拷贝的数组 Array a(10); for(int i =0;i<10;i++) { a.set(i,i+1); } a.values(); //在创建b的时候等号a,默认调用a的拷贝构造函数 Array b = a; b.set(9,10086); b.values(); b.reverse(); b.values(); //下面是调用等号操作符的复制,因为如果定义和赋值分开就是调用默认的等号操作符 //如果不重写默认是浅拷贝的 Array c; c = b; c.reverse(); c.values(); //直接用cout打印数组a cout<<a<<endl; cout<<"a==a:"<<(a==a)<<endl; cout<<"a==b:"<<(a==b)<<endl; //!=判断,巧用==反转 cout<<"a!=a:"<<(a!=a)<<endl; cout<<"a!=b:"<<(a!=b)<<endl; return 0; }
//有空可以加入快排,多变量等功能,实现完整的类python的list