Tuesday 16 February 2016

c++ - Returning pointer to protected inner class element



I have a generic Linked-List class that contains a protected inner class that holds the ListElements (nodes). In my Linked-List class, I would like to create a function that returns a pointer to the List-Element that is previous to the given argument. I am unable to figure out how to properly define and implement such a function in a generic template class.



Here is the LinkedList.h code.



template 
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;
};


I want to implement a function such as this. KEEPING IN MIND: I already know how to properly code the function, I am NOT sure how to DEFINE it in LinkedList.h and IMPLEMENT it in 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.


}


Answer



You can't declare a template method in a header file then implement it in a cpp file. Template methods have to be implemented in the header file. You can declare your methods in the class or you can implement them further down in the file. When implemented below the class your example method would look like this



template

LinkedList::ListElement *LinkedList::ListElement::getPrevious(ListElement *target){
//...
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...