C ++ to variable length array class int

/ ************************************************* *********************** 
* function: 1 can specify the number of array elements in the object initialization
* 2: play can dynamically add elements in the array
* 3: use of such, do not worry about dynamic memory allocation, release problems
* 4: arrays can be used as a dynamic array is used as the class objects, such elements can be accessed by the index. 
************************************************** ************************************************************ /


#include <the iostream> #include <CString> the using namespace STD; class CArray- { Private : int size; int * PTR; public : CArray-( int S = 0 ); CArray-( const CArray &); void push_back(int v); CArray & operator=(const CArray &); int length(); int &operator[](int i) { return ptr[i]; } ~CArray(); }; int CArray::length() { return size; } //CArray::CArray(int s=0):size(s) CArray::CArray(int s):size(s) { if(s==0) PTR = NULL; the else PTR = new new int [S]; } CArray-CArray-:: ( const CArray-S &) // NOTE parameter to const, prevent accidental changes { IF (s.size == 0 ) { size = 0 ; PTR = NULL; return ; } PTR = new new int [s.size]; the memcpy (PTR, s.ptr, the sizeof ( int ) * s.size); size =s.size; } void CArray::push_back(int v) { if(ptr) { int * tempPtr=new int[size+1]; memcpy(tempPtr,ptr,size*sizeof(int)); delete [] ptr; ptr=tempPtr; } else ptr=new int[1]; ptr[size++]=v; } CArray & CArray::operator=(constS & CArray-) // NOTE parameter const. { IF (s.ptr == PTR) return * the this ; IF (PTR) // must pay attention to prevent the null pointer delete delete [] PTR; IF (s.ptr) { PTR = new new int [s.size]; the memcpy (PTR, s.ptr, s.size * the sizeof ( int )); size = s.size; } the else { PTR = NULL; size = 0 ; } return *this; } CArray::~CArray() { if(ptr) delete [] ptr; } int main() { CArray a; for(int i=0;i<5;i++) a.push_back(i); //a[0]=11111; // for(int i=0;i<a.length();i++) // cout<<a[i]<<" "; // cout<<"aaaa\n"; 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<<a2[i]<<" "; cout<<endl; a[3]=100; CArray a4(a); for(int i=0;i<a4.length();i++) { cout<<a4[i]<<" "; } return 0; }

 

Guess you like

Origin www.cnblogs.com/cq0143/p/11300859.html