Okay so I have a class, LinkedList, with a nested class, LinkedListIterator. Within LinkedListIterator’s methods I reference the private fields of LinkedList. Which I thought was legal. But I get the error:
from this location
every time I reference them.
And I get corresponding error messages on the fields in the enclosing class:
invalid use of non-static data member 'LinkedList<int>::tail'
Any idea why? The relevant code is below:
template<class T>
class LinkedList {
private:
//Data Fields-----------------//
/*
* The head of the list, sentinel node, empty.
*/
Node<T>* head;
/*
* The tail end of the list, sentinel node, empty.
*/
Node<T>* tail;
/*
* Number of elements in the LinkedList.
*/
int size;
class LinkedListIterator: public Iterator<T> {
bool add(T element) {
//If the iterator is not pointing at the tail node.
if(current != tail) {
Node<T>* newNode = new Node<T>(element);
current->join(newNode->join(current->split()));
//Move current to the newly inserted node so that
//on the next call to next() the node after the
//newly inserted one becomes the current target of
//the iterator.
current = current->next;
size++;
return true;
}
return false;
}
You can’t just use non-
staticmembers like that. I think the following example will clear things out:What would
currentandtailbe inside the method? There’s no instance ofLinkedListto speak of, so those members don’t even exist yet.I’m not saying make the members
static, that would be wrong, but re-think your approach.Look into how
stditerators are.