// This is the Node.h file
#ifndef NODE
#define NODE
template <typename T>
class Node
{
private:
T elem;
Node *next;
friend class LinkedList<T>;
};
#endif // NODE
This is the LinkedLilst.h file
#ifndef LINKED_LIST
#define LINKED_LIST
#include "Node.h"
template <typename T>
class LinkedList
{
public:
LinkedList();
~LinkedList();
bool empty() const;
const T &front() const;
void addFront(const T &e);
void removeFront();
private:
Node<T> *head;
};
#endif // LINKED_LIST
This is the LinkedList.cpp file
#include <iostream>
#include "LinkedList.h"
using namespace std;
template <typename T>
LinkedList<T>::LinkedList() : head(NULL) {}
template <typename T>
bool LinkedList<T>::empty() const // I don't want it to modify the data member of the function.
{
return head == NULL;
}
template <typename T>
LinkedList<T>::~LinkedList()
{
while (!empty())
removeFront();
}
...
...
...
This is my main.cpp file
#include <iostream>
#include "LinkedList.h"
using namespace std;
int main()
{
LinkedList<int> ls;
ls.addFront(3);
cout << ls.front();
return 0;
}
I don't know why I am getting the error: 'LinkedList' is not a class template
friend class LinkedList<T>; in Node.h
The problem is that Node.h file doesn't have anything related to LinkedList. I added LinkedList Declaration but it still showing errors. Please help.
CodePudding user response:
You need to forward declare the LinkedList
class template:
#ifndef NODE
#define NODE
template<class> class LinkedList; // <- forward declaration
template <typename T>
class Node
{
private:
T elem;
Node *next;
friend class LinkedList<T>;
};
#endif // NODE
The next problem you are going to run in to is probably a linking problem. I suggest moving the class member functions definitions into the header files. More on that here: Why can templates only be implemented in the header file?