I get error while trying to compile following class
Stack.cpp:28: error: expected constructor, destructor, or type conversion before ‘::’ token
#include <iostream>
using namespace std;
template <class T>
class Stack
{
public:
Stack(): head(NULL) {};
~Stack();
void push(T *);
T* pop();
protected:
class Element {
public:
Element(Element * next_, T * data_):next(next_), data(data_) {}
Element * getNext() const { return next; }
T * value() const {return data;}
private:
Element * next;
T * data;
};
Element * head;
};
Stack::~Stack()
{
while(head)
{
Element * next = head->getNext();
delete head;
head = next;
}
}
You are declaring a template class. You can either:
implement the destructor within the class declaration, like this
public:
Stack(): head(NULL) {};
~Stack() {
// ...
}
define the templated destructor outside the class declaration, like this
template <class T>
Stack<T>::~Stack()
{
// ...
}
However, if you attempt to define just Stack::~Stack()
then the compiler does not know which type T
you are implementing the destructor for.
template<typename T>
Stack<T>::~Stack()
{
//...
}
This is generally valid for every method you define outside of the class' declaration, not just the destructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With