我是第一次学习 C++ 模板,并从“Michael Goodrich 的 C++ 中的数据结构和算法”中复制了这段代码。
我收到错误“第 13 行:SLinkedList 不是模板”。我完全不知道为什么不是因为我到处都使用了“模板”。
// ------------------ DEFINITION FOR NODE ------------------------
template <typename E>
class SNode{
private:
E elem;
SNode<E>* next;
friend class SLinkedList<E>;
public:
SNode(E element = NULL);
const E getElem() const;
void setElem(E element);
};
template <typename E>
SNode<E>::SNode(E element){ elem = element;}
template <typename E>
const E SNode<E>::getElem() const
{return elem;}
template <typename E>
void SNode<E>::setElem(E element)
{elem = element;}
// -------------------- DEFINITION FOR SINGLY-LINKED LIST --------------
template <typename E>
class SLinkedList
{
private:
SNode<E>* head;
public:
SLinkedList();
~SLinkedList();
bool isempty() const;
const E& infront() const;
void addfront(const E& e);
void removefront();
};
template <typename E>
SLinkedList<E>::SLinkedList()
:head(NULL) {}
template <typename E>
SLinkedList<E>::~SLinkedList()
{while(!isempty()) removefront();}
template <typename E>
bool SLinkedList<E>::isempty() const
{return (head == NULL);}
template <typename E>
const E& SLinkedList<E>::infront() const {return head->elem;}
template <typename E>
void SLinkedList<E>::addfront(const E& element) {
SNode<E>* v = new SNode<E>;
v->elem = element;
v->next = head;
head = v;
}
template <typename E>
void SLinkedList<E>::removefront() {
SNode<E>* old = head;
head = old->next;
delete old;
}
int main()
{
std::cout<<"Checking SLinkedList ..."<<std::endl<<std::endl;
SLinkedList<int> intList;
intList.addfront(13);
std::cout<<intList.head->next->getElem();
return 0;
}