我正在编写一些模板化的数据结构供将来使用,并且我的单链表和图表实现中都有一个类Node
。这些标题中的每一个都有标题保护,但我仍然遇到重定义错误:
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;
}
我知道这些类是不完整的,我知道没有必要重新发明轮子,因为我需要的所有东西都存在于std
中,但有人可以解释为什么类节点有重新定义错误吗?
我的假设是编译器没有看到SINGLY_LINKEDLIST_H
的定义,因此它为其类中的所有内容创建了一个定义;然后它再次看不到GRAPH_H
并尝试为Graph
类中的所有内容创建一个定义错误的定义。
如果是这样,我该怎么办?创建一个单独的Node
类?创建一个Node
标题,其中包含两个数据结构可能需要的内容?
只是寻找提示。
谢谢, erip
答案 0 :(得分:3)
您需要:
Node
类分解为单独的头文件。Node
类以区分。Node
类放入不同的名称空间。正如您的问题所示,两个头文件都包含Node
类的定义,您对编译器感到困惑。