【发布时间】:2015-04-13 10:23:39
【问题描述】:
我正在使用模板类对链表进行分配。
在我的 main.cpp 中,我应该能够创建列表(有效)并使用赋值运算符或复制构造函数创建另一个列表。这是我的代码:
template <class T>
LinkedList<T>::LinkedList(const LinkedList<T>& other)
{
Node<T>* tmp = other.getLeader(); //LINE WHERE THE ERROR OCCURS
for(int i = 0; tmp != NULL; i++)
{
insert(i, tmp->element);
tmp = tmp->next;
}
}
template <class T>
Node<T>* LinkedList<T>::getLeader()
{
return head;
}
错误显示:
linkedList.C:61:6: error: passing ‘const LinkedList<int>’ as ‘this’ argument
of ‘Node<T>* LinkedList<T>::getLeader() [with T = int]’
discards qualifiers [-fpermissive] tmp = other.getLeader();
Main.cpp:
int main()
{
LinkedList<int> list;
list.insert(0, 0);
list.insert(1, 1);
list.insert(2, 2);
cout << list;
LinkedList<int> list2(list);
cout << list2;
return 0;
}
element 和 next 是 Node 类的公共变量。
请注意,由于这项任务的性质,我不能只更改类定义,只更改类的实现。
编辑:
template <class T>
LinkedList<T>::LinkedList(const LinkedList<T>& other) // I CANNOT CHANGE THIS
{
// I CAN CHANGE THIS
}
【问题讨论】:
-
您是否使用
new在插入中进行深层复制?你默认head为nullptr吗?编辑:这与您的编译器错误无关,只是我自己的熏陶。 -
您的错误是因为
getLeader()不是常量。修复它。 -
旁注——我赞赏在您的复制构造函数中,您没有在
insert函数中重新实现代码,而是重用了它。太多的新手犯了在他们的复制构造函数中重写整个insert功能的错误。
标签: c++ copy-constructor singly-linked-list