Some older compilers do not support variable-length arrays, such as VC6.0, VS2010, and so on, which sometimes inconvenience programming, and we implement variable-length arrays by customizing the array class. Specifically, the need for a copy constructor is explicitly defined.
#include <iostream> #include <cstdlib> using namespace std;
Variable-length array class array{public:array (int len); Array (const array &arr);
Copy constructor ~array (); Public:int operator[] (int i) const {return m_p[i];} Get element (read) int &operator[] (int i) {return m_p[i];}
Gets the element (write) int length () const {return m_len;} private:int M_len;
int *m_p;
};
Array::array (int len): M_len (len) {m_p = (int*) calloc (len, sizeof (int));}
Array::array (const Array &arr) {//copy constructor This->m_len = Arr.m_len;
This->m_p = (int*) calloc (This->m_len, sizeof (int));
memcpy (this->m_p, arr.m_p, M_len * sizeof (int));
} array::~array () {free (m_p);}
Print array element void PrintArray (const array &arr) {int len = arr.length ();
for (int i=0; i<len; i++) {if (i = = len-1) {cout<<arr[i]<<endl;
}else{cout<<arr[i]<< ",";
int main () {Array arr1 (10); for (int i=0; i<10; i++) {Arr1[i] = i;
} Array arr2 = arr1;
ARR2[5] = 100;
ARR2[3] = 29;
PrintArray (ARR1);
PrintArray (ARR2);
return 0; }