标头保护仍然会产生重新定义错误
Headers guards still yield redefinition errors
我正在编写一些模板化的数据结构以备将来使用,并且有一个类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
图形.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
驱动程序.cc
#include <iostream>
#include <string>
#include "SinglyLinkedList.h"
#include "Graph.h"
int main()
{
Graph<int> Hello(false);
return 0;
}
我知道这些类是不完整的,我知道没有必要重新发明轮子,因为我所需要的一切都存在于std
中,但有人能解释为什么类Node存在重新定义错误吗?
我的假设是编译器没有看到SINGLY_LINKEDLIST_H
的定义,所以它为类中的所有内容创建了一个定义;则它再次看不到CCD_ 4并且尝试为CCD_。
如果是这样,我该如何处理?是否创建单独的Node
类?制作一个Node
标头,其中包含两种数据结构可能需要的内容?
只是想找些小技巧。
谢谢,erip
您需要:
- 将
Node
类分解为单独的头文件 - 或者重命名
Node
类以进行区分 - 将
Node
类放入单独的命名空间中
如您的问题所示,两个头文件都包含Node
类的定义,并且您混淆了编译器。
相关文章:
- 定义C++新的环境变量并在 bat 文件中使用它
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 从使用概念定义的函数返回新对象
- 如何在C++中为 if 和 else 语句定义新行为
- 如何从 C++ 中的现有模板函数定义新函数
- 自定义分配器,包括放置新案例
- 正在通过const-ref未定义的行为捕获新构造的对象
- 如何在CPropertySheet中定义新颜色
- 谁定义新操作员
- 未定义的符号'fixed_address_empty_string':带有protobuf的新张量流运算
- 新的C ,未定义的参考
- boost :: fibonacci_heap:带有比较器重新定义圆形定义错误的嵌套定义
- 宏,用于定义带有添加前缀的新宏
- 取消脱壳:使用模板在多行类型定义中添加一个尖括号后的新行
- C 通过Typedef定义新类型
- 通过在此指针上放置新位置重新初始化对象时未定义的行为
- 在 ss.clear() 之后使用 ss.str( " ") 用于新定义的字符串流
- Eclipse CDT将方法定义定义到标头文件
- 是标头文件中使用“新”定义的成员指针泄漏
- LEX 程序中的未定义定义