Question

I am stumped by what seems to be a strange issue with assigning a value to a type. This is the code giving me issues:

1. ListIterator<int> itr = lst.begin();
2.itr++;
3.itr = lst.begin();

So line 1 and 2 work fine; however, when I try making itr = lst.begin() after it has been declared I get the following error:

ListMain.cpp:46: error: no match for ‘operator=’ in ‘itr = lst. List<T>::begin [with T =      int]()’
List.h:183: note: candidates are: void ListIterator<T>::operator=(ListIterator<T>&)   [with T = int]

Now my operator= is currently this:

void operator = (iterator & rhs) {theList = rhs.theList; currentLink = rhs.currentLink;}

So since my begin() function returns a ListIterator shouldn't this just reassign the list iterator or am I missing something?

Any insight to this problem would be greatly appreciated.

Was it helpful?

Solution

Your operator= takes its argument by non-const reference. As such, temporaries (such as the object returned by begin()) cannot bind to it. If you need a custom copy assignment operator, change it like this:

void operator = (const iterator & rhs) {theList = rhs.theList; currentLink = rhs.currentLink;}

In addition, to make the operator conform to the standard library requirements, you should change it to return a reference to the object being assigned to:

iterator& operator = (const iterator & rhs) {
  theList = rhs.theList;
  currentLink = rhs.currentLink;
  return *this;
}

Lastly, do you need a custom assignment operator at all? What yours does is just assignment of members. If they are all members, you're better off removing the operator entirely and relying on the compiler-generated one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top