我正在编写一个简单的链表,一切正常,但是我遇到了一些在课外定义方法时无法理解的问题。如果我在类中定义方法它完美地工作,当我声明方法并尝试在类之外定义它时,我得到编译错误......
所以这是代码工作正常时:
#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_
当我尝试在类之外实现insert方法时:(顺便说一下,VS2015允许自动执行此操作,并且由于静态绑定而在头文件中定义) 此代码不起作用,它会导致编译错误:
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;
}
在类之外定义方法:(编译错误) enter image description here
答案 0 :(得分:1)
什么是Iterator
?您需要告诉编译器Iterator
是LinkedList<T>
依赖范围的内部类。
template <typename T>
struct LinkedList
{
class Iterator
{
};
Iterator insert(Iterator, const T&);
};
template <typename T>
typename LinkedList<T>::Iterator LinkedList<T>::insert(Iterator, const T&)
{
// ...
}