dimanche 29 mars 2015

Inheritance with Nodes in C++


I'm writing a doubly linked list in C++ and have a class Node which I'm using for a singly linked list. Below shows the definition of the class.



Node.h




#ifndef NODE_H
#define NODE_H

template <class T>
class Node {
public:
Node<T>() { this = nullptr; }
Node<T>(T init) { data = init; next = nullptr; }

void setData(T newData) { data = newData; }
void setNext(Node<T> *nextNode) { next = nextNode; }

const T getData() { return data; }
Node<T> *getNext() { return next; }
private:
T data;
Node<T> *next;
};

#endif


Obviously the main difference between a singly linked list and doubly linked list is a pointer to the previous Node, so I'm trying to inherit everything from the Node class in a new class and simply add a prev attribute:



DoublyLinkedList.h




#ifndef DOUBLY_LINKEDLIST_H
#define DOUBLY_LINKEDLIST_H

#include "Node.h"

template <class T>
class DLLNode : public Node {
public:
// Inherit default constructor from Node and set prev to nullptr;
DLLNode<T>() : Node<T>(), prev() {}
// Inherit constructor from Node and set prev to nullptr;
DLLNode<T>(T init) : Node<T>(init), prev() {}

Node<T> *getPrev() { return prev; }
private:
Node<T> *prev;
};

/*
TODO: Implement doubly linked list class
*/

#endif


My driver is, simply, the following:



driver.cc




#include <iostream>
#include "DoublyLinkedList.h"

int main()
{
DLLNode<int> test;

return 0;
}


When I compile, I get the following errors:



./DoublyLinkedList.h:7:24: error: expected class name
class DLLNode : public Node {
^
./DoublyLinkedList.h:9:18: error: type 'Node<int>' is not a direct or virtual base of 'DLLNode<int>'
DLLNode<T>() : Node<T>(), prev() {}
^~~~~~~
driver.cc:6:15: note: in instantiation of member function 'DLLNode<int>::DLLNode' requested here
DLLNode<int> test;


I don't understand why the class Node isn't being recognized as a class as my compiler has claimed by the first error. Any tips would be greatly appreciated.


My compiler is Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)




Aucun commentaire:

Enregistrer un commentaire