2017-05-07 73 views
1

我需要幫助,我不知道如何註冊我的複製構造函數來執行深層複製。C++ - 複製構造函數,深拷貝和如何正確寫入

我的問題是我的複製構造函數是否正確註冊,如果不是,那麼我怎麼寫下來非常感謝。

我ArrayList.h:

template<class T> 
class ArrayList{ 
private: 
T* storage;// T pointer array 
int size;// size of array 

public: 
ArrayList();//constructor 
ArrayList(const &ArrayList);//copy constructor 
}; 

template<class T>//constructor 
ArrayList<T>::ArrayList(){ 
size = 0;// size of array in start 
}//end ArrayList 

template<class T>//copy constructor 
ArrayList<T>::ArrayList(const &ArrayList){ 
T* _storage = T* storage; 
int _size = size; 
} 

template<class T>//destructor 
ArrayList<T>::~ArrayList(){ 
delete[]storage; 
}//end ~ArrayList 

感謝的

回答

3

不,它是不正確的。現在你正在執行一個淺拷貝,也就是隻是複製指針(這是默認拷貝構造函數會做的),所以當拷貝和原始文件超出範圍時,你會得到2個析構函數試圖釋放相同的記憶和砰!

你需要在拷貝構造函數分配內存,複製的元素,然後更改指針指向新分配的內存,像

template<class T>//copy constructor 
ArrayList<T>::ArrayList(const ArrayList&){ 
    T* copy_storage = new T[size]; 

    for(std::size_t i = 0; i < size; ++i) 
     copy_storage[i] = storage[i]; 

    storage = copy_storage; 
} 

我想這是一個鍛鍊。如果不是,只需使用std::vector<T>,而所有內容都將自動處理。

+0

tahnk's。但爲什麼我得到錯誤錯誤C4430:缺少類型說明符 - 假定爲int。注意:C++不支持default-int \t c:\ projects \ template \ ArrayList.h 模板 – david

+0

@david參考符號'&'必須在**類型之後**,即'const ArrayList& '(在答案中更正),請確保相應地更改代碼。現在你也定義了析構函數,但是不要在類中聲明它,還要確保你聲明瞭析構函數。 – vsoftco

+0

謝謝我的理解。現在我得到這個錯誤:錯誤錯誤LNK1104:無法打開文件'c:\ Projects \ Template \ Release \ Template.exe'\t c:\ Projects \ Template \ LINK \t模板 – david