我是第一次学习 C++ 模板,并从“Michael Goodrich 的 C++ 数据结构和算法”中复制了这段代码。
我收到错误消息“第 13 行:SLinkedList 不是模板。”我完全不知道为什么不是因为我到处都使用"template"。
// ------------------ 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;
}
最佳答案
friend class SLinkedList<E>;
这可以是任何东西。编译器不知道它是什么。但是,如果你在声明 SNode
之前告诉他稍后将定义它......:
template <typename E>
class SLinkedList;
...它可能有效;)
关于C++ Template,第一次学习,这段代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18178727/