我正在使用类似于 java 中的 ArrayList 的 C++ 模板类(是的,我知道 vector 做同样的事情,这不是一个实用的编码项目)。
我认为为我的 ArrayList 类提供一个构造函数会很有用,它接受另一个 ArrayList 作为参数来为 ArrayList 播种。但是当我尝试编写构造函数时,我得到了这个错误
invalid constructor; you probably meant 'ArrayList<T> (const ArrayList<T>&)'
这是否意味着 ArrayList 必须是一个常数?为什么我需要 addressof 运算符?
我仍在学习 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);
}
}