0

) Hi everyone! So I have two classes named DoubleNode (represents double linked list node) and DoublyLinkedList (it's implementation). Inside the DoubleNode class I specify that DoublyLinkedList would be it's friend class, but IDE and compiler sees it as if Im redefining DoublyLinkedList class inside the DoubleNode class instead of resuming that it is just a friend class and gives an error saying "Redefinition of 'DoublyLinkedList' as different kind of symbol" here is my code:

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

One again, compiler give error "Redefinition of 'DoublyLinkedList' as different kind of symbol"

Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42

1 Answers1

0

The compiler needs to know that DoublyLinkedList is a class template before you can forward-declare its specialization.

Solution 1. Forward-declare DoublyLinkedList before class DoubleNode like this:

template <typename Type>
class DoublyLinkedList;

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

Solution 2. Add template to the friend declaration:

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

Note you don't need to repeat the Type in this case to avoid shadowing the template argument.

rustyx
  • 80,671
  • 25
  • 200
  • 267