链表节点的C ++好友类

时间:2017-05-27 07:39:22

标签: c++ xcode templates friend

)大家好! 所以我有两个名为DoubleNode(代表双链表节点)和DoublyLinkedList(它的实现)的类。在DoubleNode类中,我指定DoublyLinkedList将是它的朋友类,但是IDE和编译器认为它就好像我在DoubleNode类中重新定义DoublyLinkedList类而不是恢复它只是一个朋友类并且给出错误说& #34;重新定义' DoublyLinkedList'作为不同类型的符号"  这是我的代码:

 #ifndef DoubleNode_h
#define DoubleNode_h
using namespace std;
#include "DoublyLinkedList.h"

template <typename Type>
class DoubleNode {
private:
    Type elem;
    DoubleNode<Type>* next;
    DoubleNode<Type>* prev;
    friend class DoublyLinkedList<Type>;

    public:
    DoubleNode (Type const& e, DoubleNode* a, DoubleNode* b) {
        elem = e;
        next = a;
        prev = b;
    }

    Type getData() const {
        return elem;
    }

    DoubleNode * getNext() const {
        return next;
    }

    DoubleNode * getPrevious() const {
        return prev;
    }


};

DoublyLinkedList.h

  #ifndef DoublyLinkedList_h
#define DoublyLinkedList_h
#include "DoubleNode.h"


template <typename Type>
class DoublyLinkedList {
private:
    DoubleNode<Type>* head;
    DoubleNode<Type>* tail;
    int size;

public:
    DoublyLinkedList() {
        head = new DoubleNode<Type>;
        tail = new DoubleNode<Type>;
        head->next = tail;
        tail->prev = head;
        head->prev = nullptr;
        tail->next = nullptr;

        size = 0;
    }

    ~DoublyLinkedList() {
        while (!empty())
            pop_front();
        delete head;
        delete tail;
    }

    //Accessors
    int size() const{
        return size;
    }
    ...

再一次,编译器给出错误&#34;重新定义&#39; DoublyLinkedList&#39;作为不同类型的符号&#34;

1 个答案:

答案 0 :(得分:0)

编译器需要知道DoublyLinkedList是一个类模板才能转发声明它的特化。

解决方案1。在此DoublyLinkedList之前转发声明class DoubleNode

template <typename Type>
class DoublyLinkedList;

template <typename Type>
class DoubleNode {
private:
    . . .
    friend class DoublyLinkedList<Type>;
    . . .

解决方案2. template添加到friend声明:

template <typename Type>
class DoubleNode {
private:
    . . .
    template<typename> friend class DoublyLinkedList;
    . . .

请注意,在这种情况下,您不需要重复Type以避免隐藏模板参数。