【发布时间】:2012-08-10 02:29:40
【问题描述】:
我正在用 C++ 编写一个类似于 java 中的 ArrayList 的模板类(是的,我知道 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);
}
}
【问题讨论】:
-
请发布一个完整的最小示例
-
天哪,我忘了按 ctrl + C
-
您正在尝试编写一个复制构造函数,它必须有一个引用参数。 stackoverflow.com/questions/2685854/…
标签: c++ templates constructor