I am writing a simple linked list and everything works just fine, but I have some problems that I can't understand when it comes to defining a method outside of the class. If I define the method inside the class it works perfectly, when I declare the method and trying to define it outside of the class I get compilation errors...
So here is the code when it works fine:
#ifndef LINKEDLIST__H_
#define LINKEDLIST__H_
#pragma warning (disable: 4290)
#include "Item.h"
template<class T> class LinkedList
{
Item<T>* head;
Item<T>* tail;
public:
LinkedList(): head(new Item<T>()), tail(new Item<T>())
{
head->setNext(tail);
tail->setPrev(head);
}
~LinkedList() { delete head; } // how does that work?
class Iterator // Nested class.
{
Item<T>* p;
friend class LinkedList<T>;
public:
Iterator(Item<T>* pt = 0) : p(pt) {}
int operator!=(Iterator itr) const // Operator !=
{
return (p != itr.p);
}
Iterator& operator++(int) throw(char*) // Operator ++ (postfix)
{
if (p == NULL)
throw "null pointer in list::iterator";
p = p->getNext();
return *this;
}
Iterator& operator--(int) throw (char*) // Operator -- (postfix)
{
if (p == NULL)
throw "null pointer in list::iterator";
p = p->getPrev();
return *this;
}
T& operator*() throw (char*) // Operator *
{
if (p == NULL || p->getData() == NULL)
throw "null pointer in list::iterator";
return *(p->getData());
}
}; // End of class Iterator scope.
Iterator begin() { return head->getNext(); }
Iterator end() { return tail; }
Iterator insert(Iterator itr, const T& data)
{
// create a copy of data
Item<T>* pNewItem = new Item<T>(new T(data));
// connect
pNewItem->setNext(itr.p);
pNewItem->setPrev(itr.p->getPrev());
itr.p->getPrev()->setNext(pNewItem);
itr.p->setPrev(pNewItem);
return pNewItem;
}
Iterator erase(Iterator itr);
}; // End of class LinkedList scope.
#endif // !LINKEDLIST__H_
When I try to implement insert method outside of the class: (By the way this is how VS2015 lets do this automatically, and it is defined within the header file because of the static binding) This code doesn't work and it causes compilation error:
template<class T>
inline Iterator LinkedList<T>::insert(Iterator itr, const T & data)
{
// create a copy of data
Item<T>* pNewItem = new Item<T>(new T(data));
// connect
pNewItem->setNext(itr.p);
pNewItem->setPrev(itr.p->getPrev());
itr.p->getPrev()->setNext(pNewItem);
itr.p->setPrev(pNewItem);
return pNewItem;
}
Defining the method outside of the class: (Compilation errors) enter image description here