實現數組類(C++ 拷貝構造函數、拷貝函數)要判斷賦值左右對象不相等,坑慘了


#include <iostream>
using namespace std;
class ArrayIndexOutOfBoundsException{  // 異常類
public:
    int index;
    ArrayIndexOutOfBoundsException(int k){
        index = k;
    }
};
class Array{
private:
    int *data;
    int size;
    static const int dSize = 10;   // 數組默認大小
public:
    Array( ){  // 無參構造
        size = dSize;
        data = new int[size]( );
    }
    
        Array(int n ){  // 有參構造
        size = n;
        data = new int[size]( );
    }
    
    Array(const Array& arr)//拷貝構造函數,深拷貝
    {
    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)//如果等號右側的對象和左邊的不是一個對象再賦值(沒有這句會運行error),要判斷賦值左右對象不相等,坑慘了 
        {
        delete []data;//先釋放掉之前的內存,否則會內存超限    
        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)//不為空才釋放 
        {
            delete []data;
        }
       
    }
                
        
    int& operator [] (int k){     // 運算符 [ ] 重載,以方便數組的使用
        if(k<0 || k>=size) throw ArrayIndexOutOfBoundsException(k);
        return data[k];
    }
    friend ostream& operator << (ostream& o, const Array& a);   // 運算符 << 重載,以方便輸出
};
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;
}
// 注意:實際測試程序中,在此處之前的代碼與樣例中相同
// 注意:實際測試程序中,在此處之后的代碼(即main函數)可能與樣例中不同
int main(){
    int n, k;
    cin >> n >> k;
    Array a(n);  // 構造數組,大小為 n
    for(int i=0; i<n; i++) a[i] = i;
    Array b = a;  // 拷貝構造數組
    b[n/2] = k;
    cout << a << endl;
    cout << b << endl;
    Array c;  // 構造數組,默認大小
    c = a; // 拷貝數組
    c[n/2] = k;
    cout << a << endl;
    cout << c << endl;
    a = a;
    a[n/2] = 2223;
    cout << a << endl;
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM