Reputation: 8515
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;
}
}
Upvotes: 11
Views: 24351
Reputation: 2062
template<typename T>
Stack<T>::~Stack()
{
//...
}
This is generally valid for every method you define outside of the class' declaration, not just the destructor.
Upvotes: 7
Reputation: 181
Not sure but maybe this way...
template <class T>
Stack<T>::~Stack()
Upvotes: 2
Reputation: 994659
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.
Upvotes: 14
Reputation: 106246
If you put the function after the class definition, you must specify the template aspect again as in:
template <class T>
Stack<T>::~Stack()
{
...
}
You don't need to do that if you define the function inside the class (but that constitutes a compiler hint to inline the function which you may or may not care about).
Upvotes: 4
Reputation: 23664
Stack::~Stack()
should be
template <typename T>
Stack<T>::~Stack()
Upvotes: 6