I'm trying to implement a stack class as a learning exercise. This is my StackNode class,
template <typename T>
class StackNode{
public:
T data_{};
StackNode<T> next_;
StackNode() : data_(nullptr), next_(nullptr){}
StackNode(const T& data_) : data_(data_),next_(nullptr) {}
};
I use this node to create a Stack, this is the code,
template <typename T>
class Stack{
private:
StackNode<T> top_;
std::size_t size_{};
public:
Stack() : top_(nullptr), size_ (0){}
void push(const T& item){
StackNode<T> p{item};
p.next_ = top_;
top_ = p;
}
T pop(){
StackNode<T> p = top_;
top_ = top_.next_;
return p;
}
T peek(){
return top_.data_;
}
};
This is the calling Client,
Stack<int> stack{};
stack.push(12);
stack.push(13);
std::cout << stack.peek() << std::endl;
stack.pop();
std::cout << stack.peek() << std::endl;
I get the following compilation errors
In file included from /Users/mstewart/Dropbox/codespace/private/cpp-drive/data-structures/main.cpp:2:
In file included from /Users/mstewart/Dropbox/codespace/private/cpp-drive/data-structures/Stack.hpp:5:
/Users/mstewart/Dropbox/codespace/private/cpp-drive/data-structures/StackNode.h:12:18: error: field has incomplete type 'StackNode<int>'
StackNode<T> next_;
^
/Users/mstewart/Dropbox/codespace/private/cpp-drive/data-structures/Stack.hpp:13:18: note: in instantiation of template class 'StackNode<int>' requested here
StackNode<T> top_;
^
/Users/mstewart/Dropbox/codespace/private/cpp-drive/data-structures/main.cpp:6:16: note: in instantiation of template class 'Stack<int>' requested here
Stack<int> stack{};
^
/Users/mstewart/Dropbox/codespace/private/cpp-drive/data-structures/StackNode.h:9:7: note: definition of 'StackNode<int>' is not complete until the closing '}'
class StackNode{
^
Can someone help me understand what I'm doing wrong. I'm new to C++