我有以下代码,用作链接列表的一部分:
// copy constructor:
LinkedList<T>(const LinkedList<T> &list)
{
// make a deep copy
for (LinkedList<T>::Iterator i = list.begin(); i != list.end(); i++)
{
add(*i);
}
}
// assignment constructor
LinkedList<T>& operator= (const LinkedList<T> &list)
{
// make a deep copy
for (LinkedList<T>::Iterator i = list.begin(); i != list.end(); i++)
{
add(*i);
}
}
但是当我编译时,出现以下错误(这是我将其用作分配构造函数时的错误):
1>------ Build started: Project: AnotherLinkedList, Configuration: Debug Win32 ------
1>main.cpp
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\linkedlist.h(57): error C2662: 'LinkedList<int>::Iterator LinkedList<int>::begin(void)': cannot convert 'this' pointer from 'const LinkedList<int>' to 'LinkedList<int> &'
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\linkedlist.h(57): note: Conversion loses qualifiers
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\linkedlist.h(55): note: while compiling class template member function 'LinkedList<int> &LinkedList<int>::operator =(const LinkedList<int> &)'
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\main.cpp(20): note: see reference to function template instantiation 'LinkedList<int> &LinkedList<int>::operator =(const LinkedList<int> &)' being compiled
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\main.cpp(14): note: see reference to class template instantiation 'LinkedList<int>' being compiled
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\linkedlist.h(57): error C2662: 'LinkedList<int>::Iterator LinkedList<int>::end(void)': cannot convert 'this' pointer from 'const LinkedList<int>' to 'LinkedList<int> &'
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\linkedlist.h(57): note: Conversion loses qualifiers
1>Done building project "AnotherLinkedList.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
开始和结束的迭代器代码如下:
// get root
Iterator begin()
{
return Iterator(sp_Head);
}
// get end
Iterator end()
{
return Iterator(nullptr);
}
我该怎么办?
答案 0 :(得分:3)
根据错误消息,您的LinkedList
似乎没有可以在const对象上调用的begin()
和end()
的变体。但是,复制构造函数和赋值运算符的参数为const。您将必须添加begin()
和end()
的const版本。
想必您正在寻找类似这样的东西:
ConstIterator begin() const { Iterator(sp_Head); }
Iterator begin() { Iterator(sp_Head); }
ConstIterator end() const { ConstIterator(nullptr); }
Iterator end() { Iterator(nullptr); }
ConstIterator
是迭代器类型的一个版本,它在const元素上进行迭代……