包含了有关“=”和‘【】’的重载问题;
#include<iostream>
using namespace std;
class Cars{
private:
int size;
int* pir;
public:
Cars(int x=0);
Cars(const Cars& a);
~Cars();
void push_back(int x);
Cars& operator =(const Cars& a);
int length(){
return size;
};
int& operator[](const int x);
};
Cars::~Cars(){
if(pir)delete[] pir;
}
void Cars::push_back(int x)
{
if(!pir){
pir=new int[1];
pir[size++]=x;
return ;
}
int* pri=new int[size+1];
memcpy(pri,pir,sizeof(int)*size);
pri[size++]=x;
delete[] pir;
pir=pri;
}
Cars::Cars(const Cars& a){
if(!a.pir){
pir=NULL;
size=0;
return ;
}
size=a.size;
pir=new int[a.size];
memcpy(pir,a.pir,sizeof(int)*a.size);
}
int& Cars::operator [](const int x){
return pir[x];
}
Cars& Cars::operator =(const Cars& a){
if(pir==a.pir)return *this;
if(a.pir==NULL){
if(pir)delete[] pir;
pir=NULL;
size=0;
return *this;
}
if(size<a.size){
if(pir)delete[] pir;
pir =new int[a.size];
}
memcpy(pir,a.pir,sizeof(int)*a.size);
size=a.size;
return *this;
}
Cars::Cars(int x):size(x){
if(x==0){
pir=NULL;
}else{
pir=new int[x];
}
}
int main()
{
Cars a;//先定义一个初始化
for(int n=0;n<5;n++)
a.push_back(n);//定义一个维护数组
Cars A1,A2;
A1=a;//重构“=”,A1数组,注意,不能直接将指针偏转,要重新开辟数组
for(int n=0;n<A1.length();n++)
cout<<A1[n]<<" ";//重构“【】”
cout<<endl;
A1=A2;
for(int n=0;n<A1.length();n++)
cout<<A1[n]<<" ";
cout<<endl;
A2=100;//定义初始化
Cars A3(a);//定义复制构造函数
for(int n=0;n<A3.length();n++)
cout<<A3[n]<<" ";
cout<<endl;
return 0;
}