标头保护仍然会产生重新定义错误

Headers guards still yield redefinition errors

本文关键字:新定义 定义 错误 保护      更新时间:2023-10-16

我正在编写一些模板化的数据结构以备将来使用,并且有一个类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类的定义,并且您混淆了编译器。