问题
I have the following code, used as a part of a Linked List:
// 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);
}
}
But when I compile I get the following errors (this is when I use it as an assignment constructor):
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 ==========
The iterator code for begin and end looks like this:
// get root
Iterator begin()
{
return Iterator(sp_Head);
}
// get end
Iterator end()
{
return Iterator(nullptr);
}
What do I do wrong?
回答1:
Based on the error message, it would seem that your LinkedList does not have variants of begin() and end() that can be called on a const object. The parameters to your copy constructor and assignment operator are const, however. You will have to add const versions of begin() and end().
Presumably, you're looking for something like this:
ConstIterator begin() const { Iterator(sp_Head); }
Iterator begin() { Iterator(sp_Head); }
ConstIterator end() const { ConstIterator(nullptr); }
Iterator end() { Iterator(nullptr); }
Where ConstIterator is a version of your iterator type that iterates over const elements…
来源:https://stackoverflow.com/questions/58942117/problems-with-copy-and-assignment-constructor