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

标签 c++ templates clone

美好的一天

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

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

关于c++ - "invalid initialization of non-const reference of type..."clone()函数出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28460418/

相关文章:

c++ - 如何更改 Media Foundation Transform 输出帧(视频)大小?

c++ - 使用样式表加载文件时出现 TinyXML-2 错误

c++ - 放宽对枚举类和 bool 模板参数的 constexpr 要求

c++ - 带有模板参数的模板特化

multithreading - 在多线程(使用克隆)程序中调试段错误

javascript - 有没有办法克隆 javascript 中的 native 函数,例如 window.alert 或 document.write

c++ - Linux 上的预编译头警告(太短,无法成为 PCH 文件)

c++ - "most people seriously overuse casts"怎么办?

c++ - 模板可以扩展 C++ 函数中的类吗?

git - 如何从服务器端口 9418 克隆存储库?