include [HTML_REMOVED]
include [HTML_REMOVED]
using namespace std;
class Carray
{
public:
int size;
int *ptr;
public :
Carray (int a = 0); // 元素个数
Carray (const Carray& a);// 构造函数
~Carray (); //析构函数
void push_buck (int a); // 插入函数
int length () { return size ;};// 求size
Carray& operator =(const Carray& a);//同类型之间进行赋值;
int& operator [] (int i) { return ptr[i]; };
};
Carray :: Carray (int a):size (a)
{
if (a == 0)
ptr = NULL;
else
ptr = new int [a];
return;
}
Carray :: Carray (const Carray& a)
{
if (!a.ptr)
{
ptr = NULL;
size = 0;
return;
}
ptr = new int [a.size];
size = a.size;
memcpy (ptr , a.ptr , sizeof (int) * a.size);
return;
}
Carray :: ~Carray ()
{
if (!ptr)
{
return;
}
else
delete [] ptr;
return ;
}
Carray& Carray :: operator = (const Carray& a)
{
if (ptr == a.ptr)
return this;
if (!a.ptr)
{
if (ptr) delete [] ptr;
ptr = NULL;
size = 0;
return this;
}
// 为空时不需要memcpy
if (size < a.size)
{
if (ptr) delete [] ptr;
ptr = new int [a.size];
}
memcpy (ptr , a.ptr , sizeof (int) * a.size);
size = a.size;
return *this;
// 判断空间是否够大
}
void Carray :: push_buck (int a)
{
if (ptr)
{
int* tmpptr = new int [size + 1];
memcpy (tmpptr , ptr , sizeof (int) * size);
delete [] ptr;
ptr = tmpptr;
}
else
{
ptr = new int [1];
}
ptr[size ++] = a;
}
int main ()
{
Carray a;
for (int i = 0;i < 5; i)
{
a.push_buck (i);
}
Carray a2 , a3;
a2 = a;
for (int i = 0 ;i < a.length (); i)
{
cout << a2[i] <<” “;
}
a2 = a3;
for (int i = 0;i < a2.length ();++ i)
cout << a[i] << ‘ ‘;
cout << endl;
a[3] = 100;
Carray a4 (a);
for (int i = 0;i < a4.length (); ++ i)
cout << a4[i] << ' ';
cout << endl;
return 0;
}