I'm writing some templated data structures for future use and have a class Node
that appears in both my singly linked list and graph implementations. Each of these headers have header guards, but I'm still getting an error of redefinition:
In file included from driver.cc:4:
./Graph.h:7:7: error: redefinition of 'Node'
class Node {
^
./SinglyLinkedList.h:5:7: note: previous definition is here
class Node {
^
1 error generated.
SinglyLinkedList.h
#ifndef SINGLY_LINKEDLIST_H
#define SINGLY_LINKEDLIST_H
template <class T>
class Node {
public:
Node<T>() {}
Node<T>(T init) { data = init; }
void setData(T newData) { data = newData; }
void setNext(Node<T> *nextNode) { next = nextNode; }
const T getData() { return data; }
const Node<T> *getNext() { return next; }
private:
T data;
Node<T> *next;
};
template <class T>
class SLL {
public:
SLL<T>() { head = NULL; }
private:
Node<T> *head;
};
#endif
Graph.h
#ifndef GRAPH_H
#define GRAPH_H
#include <vector>
template <class T>
class Node {
public:
Node<T>() {};
Node<T>(T init) { data = init; }
private:
T data;
};
template <class T>
class Edge {
public:
Edge<T>(Node<T> a, Node<T> b);
private:
Node<T> to;
Node<T> from;
};
template <class T>
class Graph {
public:
Graph<T>(bool direction) { directed = direction; }
const bool getDirection() { return directed; }
private:
std::vector<Edge<T> > adjList;
bool directed;
};
#endif
driver.cc
#include <iostream>
#include <string>
#include "SinglyLinkedList.h"
#include "Graph.h"
int main()
{
Graph<int> Hello(false);
return 0;
}
I know the classes are not complete and I know there's no need to reinvent the wheel because everything I'll ever need exists in std
, but can someone explain why there's a redefinition error of the class Node?
My assumption is that the compiler doesn't see a definition of SINGLY_LINKEDLIST_H
, so it creates a definition for everything in its class; then it again doesn't see GRAPH_H
and attempts to create a definition for everything in the Graph
class which yields an error.
If this is so, how should I proceed? Create a separate Node
class? Make a Node
header which has things that might be needed for both data structures?
Just looking for tips.
Thanks, erip