Implement array class (C ++ copy constructor, the copy function) is determined to be about assignment objects are not equal, the pit miserable

#include <iostream>
using namespace std;
class ArrayIndexOutOfBoundsException {// exception class
public:
    int index;
    ArrayIndexOutOfBoundsException(int k){
        index = k;
    }
};
class Array{
private:
    int *data;
    int size;
    static const int dSize = 10; // default size array
public:
    Array () {// constructor with no arguments
        size = dSize;
        data = new int[size]( );
    }
    
        Array (int n) {// configuration parameters have
        size = n;
        data = new int[size]( );
    }
    
    Array (const Array & arr) // copy constructor, deep copy
    {
    if(arr.size>0)    
 	{ 

		size = arr.size;
        data = new int[size]( );
        for (int i = 0; i < size; i++)
        {
            data[i] = arr.data[i];
        }
    }
  }
	
	Array& operator = (const Array& arr)
	{
		if (this! = & arr) // If the right side of the equal sign and the object on the left is not an object by assignment (no sentence will run error), to judge about the assignment objects are not equal, pit miserable 
		{
		delete [] data; // first memory freed before, otherwise they would Memory Limit	
	    size = arr.size;
        data = new int[size]( );
        for (int i = 0; i < size; i++)
        {
            this->data[i] = arr.data[i];
        }
    	}
		
		return *this;
	}
    
    ~Array() 
    {
        if (this-> data! = NULL) // not empty before release 
        {
            delete []data;
        }
       
    }
				
		
    int & operator [] (int k) {// operator [] overloaded, to facilitate the use of the array
        if(k<0 || k>=size) throw ArrayIndexOutOfBoundsException(k);
        return data[k];
    }
    friend ostream & operator << (ostream & o, const Array & a); // << operator overloading, to facilitate output
};
ostream& operator << (ostream& o, const Array& a){
    o << '[' ;
    for(int i=0; i<a.size-1; i++)
        o << a.data[i] << ',' ;
    o << a.data[a.size-1] << ']';
    return o;
}
// Note: The actual test program, the same as in the previous code sample in here
// Note: The actual test program, the code (that is, the main function) after here may differ from those in the sample
int main () {
    int n, k;
    cin >> n >> k;
    Array a (n); // array configuration, size n
    for(int i=0; i<n; i++) a[i] = i;
    Array b = a; // copy constructor array
    b[n/2] = k;
    cout << a << endl;
    cout << b << endl;
    Array c; // array configuration, the default size
    c = a; // copy array
    c[n/2] = k;
    cout << a << endl;
    cout << c << endl;
    a = a;
    a[n/2] = 2223;
    cout << a << endl;
    return 0;
}

  

Guess you like

Origin www.cnblogs.com/cstdio1/p/11080172.html