2017-05-27 52 views
0

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

#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; 
    } 
    ... 

一个再次,编译器给错误‘的重新定义‘DoublyLinkedList’作为不同的符号’

+1

欢迎来到Stack Overflow。请花些时间阅读[The Tour](http://stackoverflow.com/tour),并参阅[帮助中心](http://stackoverflow.com/help/asking)中的资料,了解您可以在这里问。 –

+0

πάνταῥεῖ它在这里。如果在 – Swift

+0

@Swift THX之间没有任何文字,SO就会将源文件块合并到一起,以便找到该文件。 –

回答

0

编译器需要知道DoublyLinkedList是一个类模板,然后才能转发它的专业化。

template <typename Type> 
class DoublyLinkedList; 

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

解决方案2.添加templatefriend声明:

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

注意你不需要

解决方法1.class DoubleNode这样的前前向申报DoublyLinkedList在这种情况下重复Type以避免模板论证的阴影吨。

+0

啊!谢谢 )!你的答案有帮助! –