我在模板上工作類似於java中的ArrayList的C++類(是的,我知道矢量做同樣的事情,這不是一個功利的編碼項目)。新的C++模板類構造函數,它本身的類型作爲參數
我覺得爲我的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);
}
}
請發佈一個完整的,最簡單的例子 – 2012-08-10 02:30:34
哦,狗屎我忘了點擊ctrl + C – Ethan 2012-08-10 02:31:03
你正試圖編寫一個拷貝構造函數,它必須有一個引用參數。 http://stackoverflow.com/questions/2685854/why-should-the-copy-constructor-accept-its-parameter-by-reference-in-c – aschepler 2012-08-10 02:35:55