C ++模板,第一次学习,这段代码有什么问题?

时间:2013-08-12 02:20:58

标签: c++ templates

我是第一次学习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;
}

2 个答案:

答案 0 :(得分:2)

您在宣布之前使用SLinkedList<E>。在你的“SNode”类中使用它之前,请声明它被称为前向声明。

答案 1 :(得分:2)

friend class SLinkedList<E>;

这可以是任何东西。编译器不知道它是什么。但是如果你在声明SNode之前告诉他,它将在稍后定义......:

template <typename E>
class SLinkedList;

......它可能有用;)