[英]New C++ Template class Constructor that takes a type of itself as an argument
我正在使用類似於Java中的ArrayList的C ++中的模板類(是的,我知道vector可以做到這一點,這不是一個實用的編碼項目)。
我認為為我的ArrayList類創建一個構造函數會很有用,該構造函數將另一個ArrayList作為參數植入ArrayList。 但是當我嘗試編寫構造函數時,出現此錯誤
invalid constructor; you probably meant 'ArrayList<T> (const ArrayList<T>&)'
這是否意味着ArrayList必須為常數? 為什么我需要運算符的地址?
我仍然在學習C ++的知識,所以有點困惑。
原型在這里:
ArrayList(ArrayList<T> list);
ArrayList(ArrayList<T> list, int size);
代碼在這里:
/**
* Creates an ArrayList of type T that is twice the
* size of the passed in ArrayList, and adds all elements
* from the passed ArrayList<T> list, to this ArrayList.
*
* Runs in O(n) time, where n = the size of list.
*
* @param list the ArrayList to use as a seed for this ArrayList.
*/
template<class T>
ArrayList<T>::ArrayList(ArrayList<T> list) {
array = new T[list.getSize() * 2];
capacity = list->getSize() * 2;
size = list->getSize();
for (int i = 0; i < list->getSize(); i++) {
array[i] = list->get(i);
}
}
編輯下面的代碼沒有錯誤,而上面的沒有.....
/**
* Creates an ArrayList of type T that has a capacity equal to the passed
* in theCapacity parameter. This ArrayList starts with the passed ArrayList.
*
* Note: If the passed in capacity is smaller than the size of the passed in
* ArrayList, then the capacity is set to twice the size of the
* passed ArrayList.
*
* @param list the ArrayList to use as a seed for this ArrayList.
* @param theCapacity the capacity for this ArrayList.
*/
template<class T>
ArrayList<T>::ArrayList(ArrayList<T> list, int theCapacity) {
if (theCapacity >= list->getSize()) {
array = new T[theCapacity];
capacity = theCapacity;
}
else {
array = new T[list->getSize() * 2];
capacity = list->getSize() * 2;
}
size = list->size;
for (int i = 0; i < size; i++) {
array[i] = list->get(i);
}
}
使用
ArrayList<T>::ArrayList(const ArrayList<T>& list)
作為構造函數簽名,以將arraylist作為const
引用傳遞。 這是復制構造函數的正確簽名。 除非您要在ctor中修改list
,否則實現和調用代碼都不需要更改。
當您執行ArrayList<T>::ArrayList(ArrayList<T> list)
您將創建整個ArrayList實例的臨時副本。 (您不必對ctor執行此操作,因為它將調用無限遞歸,因為list
的新副本將使用相同的函數定義,依此類推)。
ArrayList<T>::ArrayList(ArrayList<T>& list)
將列表作為引用傳遞,這意味着它不再是通常所說的“按值傳遞”,並且可以從調用代碼中處理列表的確切版本。
通過在函數中接受const引用,您就是說該函數將不會修改引用的內容(即,不對其執行任何修改操作:它將僅限於const
訪問)。 在繼續之前,您應該閱讀有關const
,引用和復制構造函數的信息。
更新:
對於按值或引用傳遞,可以通過obj.member
語法訪問成員。 如果要傳遞類似ArrayList<T>::ArrayList(ArrayList<T>* list)
的指針,則必須使用list->member
語法或(*list).member
語法,更不用說檢查list是否為0
/ nullptr
首先(您不能取消引用空指針)。
您正在混合指針的語法和值/引用的語法。 將所有list->x
轉換為list.x
因為您沒有使用指針傳遞list
參數。
有關其他傳遞行為,請參見以下內容: http : //ideone.com/3c5mJ
之所以使用“ const”,是因為它是對某些對象的引用,您將不會對其進行更改。 使用引用,因為這是副本構造函數,默認語法假定引用。
但最重要的是:您可以按照與嘗試編寫的方式完全相同的方式定義和使用此構造器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.