I wrote this something-like-stack data structure:
template<class T>
class Stos {
class Element {
public:
T n开发者_JS百科;
Element* prev;
Element(const T& k = 0): n(k), prev(0) {}
};
Element* member;
Stos(Stos&);
public:
Stos(const T&);
~Stos();
unsigned int count;
T get();
Element* push(const T&);
T pop();
void mod(const T&);
};
And implementation (same file):
template<class T>
Stos<T>::Stos(const T& n = 0): count(1) {
member = new Element(n);
}
template<class T>
T Stos<T>::get() {
return member->n;
}
template<class T>
Stos<T>::Element* Stos<T>::push(const T& n = 0) {
Element* point = member;
member = new Element;
member->prev = point;
if(n != 0) member->n = n;
++count;
return member;
}
template<class T>
T Stos<T>::pop() {
Element* point = member;
T n = point->n;
member = point->prev;
--count;
delete point;
return n;
}
template<class T>
void Stos<T>::mod(const T& n) {
member->n = n;
}
template<class T>
Stos<T>::~Stos() {
while(member) pop();
}
And when I try to compile it with g++, I get this error about the first line of definition of Stos::Element* Stos::push()
: expected constructor, destructor, or type conversion before ‘*’ token
. It is my first try to write something with templates. This stack code did work without templates, when I'd edited it, then I got the error, everything worked just fine before with "int" everywhere instead of "T".
And I can't find out why it doesn't compile. Can't I use pointer to class::member?
You need to prefix the name Element
with typename
typename Stos<T>::Element* Stos<T>::push(const T& n = 0)
Here's a link to a full explanation of why this is necessary
- http://pages.cs.wisc.edu/~driscoll/typename.html
You should also consider using
const T &n = T()
instead of
const T &n = 0
Since not all possible T may be able to be initialized from 0!
精彩评论