2015-06-21 77 views
1

我有一个通用的链接列表类,其中包含一个受保护的内部类,该类包含ListElements(节点)。在我的链接列表类中,我想创建一个函数,该函数返回指向给定参数前面的List-Element的指针。我无法弄清楚如何在泛型模板类中正确地定义和实现这样的函数。返回指向受保护的内部类元素的指针

这里是LinkedList.h代码。

template <typename Type> 
class LinkedList 
{ 
    public: 
     LinkedList(); 
     LinkedList(const LinkedList &src); 
     ~LinkedList(); 

     void insert(const Type &item, int); 
     void remove(); 
     Type retrieve() const; 
     int gotoPrior(); 
     int gotoNext(); 
     int gotoBeginning(); 
     void clear(); 
     int empty() const; 
     void printList(); 
    protected: 
     class ListElement 
     { 
      public: 
       ListElement(const Type &item, ListElement* nextP): 
        element(item), next(nextP) {} 
       Type element; 
       ListElement* next; 
     }; 
     ListElement *head; 
     ListElement *cursor; 
}; 

我想实现这样的功能。记住:我已经知道如何正确编码的功能,我不知道如何界定它LinkedList.h并执行它在LinkedList.cpp

ListElement *LinkedList::ListElement getPrevious(ListElement *target){ 
    //where a list element inside the list is passed and this returns 
    //the node previous to that. 

}

+0

为什么要重新发明轮子。标准::名单? –

+0

这是一次学习体验。在现实世界的应用程序中,我将使用std :: List,但现在我想了解这种情况的机制和适当的语法。 –

+0

说你已经知道如何正确编写函数的代码是什么意思? –

回答

1

你不能声明头文件中的模板方法然后在cpp文件中实现它。模板方法必须在头文件中实现。你可以在类中声明你的方法,或者你可以在文件中进一步实现它们。当在类下实现时,您的示例方法看起来像这样

template<typename Type> 
LinkedList<Type>::ListElement *LinkedList<Type>::ListElement::getPrevious(ListElement *target){ 
    //... 
} 
相关问题