Reputation: 1386
I'm super new to C++. I need to write a Linked List class that uses list
. I'm most of the way there, but I need a []
operator that returns the nth element in the list. I have this working in most cases, but in my test driver I need to compare two elements from different lists. (I.e. l1[n]==l2[m]
). This gives the following compile error:
error: passing ‘const StrList {aka const TList<std::basic_string<char> >}’ as ‘this’ argument of ‘T& TList<T>::operator[](int) [with T = std::basic_string<char>]’ discards qualifiers [-fpermissive]
I think the problem here is that my return call from the iterator in the []
operator is returning a const reference. (The return call from the []
operator is return(*iter);
, where *iter
refers to the correct element.
Is there a way to return the reference to the iterator as a non-const reference, or is there some other way I should be going about this? I can post more code if it's necessary.
Upvotes: 0
Views: 233
Reputation: 26040
It's slightly hard to tell without code, but given the error, you likely need a const
overload of operator[]
:
template <typename T>
const T& operator[](std::size_t n) const
{
...
}
Upvotes: 4