美好的一天
我正忙于用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/