0

I am trying to implement a generic Linked list in C++ and I get an error that I don't know how to deal with.

Here is my Link class implementation (which is also generic):

#ifndef LINK_H
#define LINK_H
#include <iostream>
#include "typeinfo.h"
#include "LinkedList.h"

template <class T>
class Link
{
    public:
    //|-------------------- Constructors --------------------
        Link(T data): m_data(data), next(NULL){}
    //|-------------------- Methods --------------------
         T getData(){
            return m_data;
         }

         T& getNext(){
            return next;
         }

         void setNext(Link* newLink){
            next = newLink;
         }

         void setData(T data){
            m_data = data;
         }
    //|-------------------- Operator overload --------------------
        bool operator==(Link& other){
            if(this->m_data == other.m_data)
                return true;
            return false;
        }

        void operator++(){

            this = this->next;
        }

    //|-------------------- Friend functions --------------------

    friend std::ostream& operator<<(std::ostream& out,const Link<T>& link){

        out<<link.m_data;
        return out;
    }

    //|-------------------- Destructor --------------------
        virtual ~Link(){}

    protected:

    private:
    //|-------------------- Private fields --------------------
        T m_data;
        Link<T>* next;

    friend class LinkedList<T>
};

#endif // LINK_H

As you can see I am trying to let LinkedList<T> be a friend of Link<T> so I can get access to its fields (I want them to stay private).

Now, I think its relevant to post all of my LinkedList<T> implementation because its a lot of code, but here's how I defined the class:

#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include "List.h"
#include "Link.h"

template <class T>
class LinkedList : public List<T>
{
    public:

and here are the fields:

   private:

    //|-------------------- Private fields --------------------
        Link<T>* head;

Now, I get this error:

error: 'LinkedList' is not a class template

I have tried to search the error and found this. But it does not seem to be the problem in my implementation.

I also found this. But I could not understand how to implement this forward declaration in my case (or why I even need it).

I'd really appreciate clarification here.

Thanks in advance

digito_evo
  • 3,216
  • 2
  • 14
  • 42

1 Answers1

1

Simply add a forward declaration of LinkedList before the definition of the Link class like this:

template<typename U>
class LinkedList;

// Now the definition as you have it above...
template <class T>
class Link
{ 
    public:
...

See here.

BTW, you're missing a ; after your friend declaration in your first code block.

florestan
  • 4,405
  • 2
  • 14
  • 28