繁体   English   中英

新的C ++模板类构造函数,将自身的类型作为参数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM