"invalid initialization of non-const reference of type..." clone() 函数出错

"invalid initialization of non-const reference of type..." Error in clone() function

美好的一天

我正忙于用c++实现线性数据结构。我正在为我的 clone() 函数而苦苦挣扎。一行代码对我来说似乎是有序的,但也许错误出在复制构造函数中。 我得到的错误: linkedList.C:22:32: 错误:从类型为“LinkedList*”的右值对类型为“LinkedList&”的非常量引用的初始化无效 return 新链表(*this);

template<class T>
LinkedList<T>& LinkedList<T>::clone()
{
    return new LinkedList<T>(*this);
}

template<class T>
LinkedList<T>::LinkedList(const LinkedList<T>& other)
{

    Node<T>* newNode;
    Node<T>* current;
    Node<T>* trailCurrent;

    if(head != NULL)
        clear();
    if(other.head == NULL)
        head = NULL;
    else
    {
        current = other.head;
        head = new Node<T>(current->element);
        head->next = NULL;

        trailCurrent = head;
        current = current->next;

        while(current != NULL)
        {
            newNode = new Node<T>(current->element);
            trailCurrent->next = newNode;

            trailCurrent = current;
            current = current->next;
        }
    }
}

您可以将克隆函数更改为:

template<class T>
LinkedList<T>* LinkedList<T>::clone()
{
    return new LinkedList<T>(*this);
}

调用克隆函数后记得释放内存。