Reputation: 2845
I want to make my own linkedlist implementatin in c++ using templates. However, I run into several compiler errors. Here is the code:
template <class T>
class Node{
T datum;
Node _next = NULL;
public:
Node(T datum)
{
this->datum = datum;
}
void setNext(Node next)
{
_next = next;
}
Node getNext()
{
return _next;
}
T getDatum()
{
return datum;
}
};
template <class T>
class LinkedList{
Node<T> *node;
Node<T> *currPtr;
Node<T> *next_pointer;
int size;
public:
LinkedList(T datum)
{
node = new Node<T>(datum);
currPtr = node; //assignment between two pointers.
size = 1;
}
void add(T datum)
{
Node<T> *temp = new Node<T>(datum);
(*currPtr).setNext((*temp));
currPtr = temp;
size++;
}
T next()
{
next_pointer = node;
T data = (*next_pointer).getDatum();
next_pointer = (*next_pointer).getNext();
return data;
}
int getSize()
{
return size;
}
};
when I try to instantiate this class, I got the following errors:
LinkedList.cpp: In instantiation of `Node<int>':
LinkedList.cpp:35: instantiated from `LinkedList<T>::LinkedList(T) [with T = int]'
LinkedList.cpp:60: instantiated from here
LinkedList.cpp:7: error: `Node<T>::_next' has incomplete type
LinkedList.cpp:5: error: declaration of `class Node<int>'
make[2]: *** [build/Debug/Cygwin-Windows/LinkedList.o] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2
I'm using NetBeans IDE. Could anybody give me some suggestion to improve it? Thanks a lot!!
Upvotes: 0
Views: 2998
Reputation: 28583
Just like when you do Node<T> *node;
in the LinkedList
, you need to also do the same in your Node
class
template <class T>
class Node{
T datum;
Node<T> *_next;//template parameter
//also, need to make this a pointer and initialized in constructor
public:
//...
void setNext(Node<T> next) //template parameter
{
_next = next;
}
Node<T> getNext() //template parameter
{
return _next;
}
//...
};
Upvotes: 1
Reputation: 13892
It might just be this line:
Node _next = NULL;
You really need that to be a pointer (Node<T>* _next
). If a class contained an instance of its own type, then THAT instance would have its own instance of that type and so on ad memorum exhaustum.
Upvotes: 1
Reputation: 2270
Your Node
class should contain a pointer to the next Node
, not a Node
directly. Here you've a recursive type which is impossible to handle for the compiler.
Another mistake is that you cannot initialize a member like this. You must do that in the constructor.
So, replace Node _next = NULL;
by Node *_next;
and initialize the pointer _next
to nullptr
in your constructor.
Upvotes: 1
Reputation: 258698
Besides the syntax being wrong:
class Node{
T datum;
Node _next = NULL;
//....
you can't have a member of the same type as a member. You can use a pointer though:
template <class T>
class Node{
T datum;
Node<T>* _next;
and set it in the constructor (because =NULL
wouldn't be legal there).
Related: Why is a class allowed to have a static member of itself, but not a non-static member?
Upvotes: 1