more template questions

T

Tony Johansson

Hello Experts!

Assume I have the following template classes which are Stack and Element see
below.
I have removed all kinds of exeption just to get a shorter code.
The code below is not complete.
I wonder if I could have something in main like
Stack<Element<T> > s;
because the stack contains of element of type Element.
Im I right.
What changes should then has to be done in this present code.

template<class U>
class Element;

template <class T>
class Stack
{
public:
Stack() : first(0) {}
~Stack();
void push(T d);
void pop();
T top();
bool empty();
private:
Element<T> *first;
Stack(const Stack&) {}
Stack& operator= (const Stack&) {}
};

template <class T>
void Stack<T>::push( T d)
{
first = new Element<T>(first, d);
}

template <class T>
Stack<T>::~Stack()
{
while(!empty() )
{
Element<T> *p = first;
first = first->next;
delete p;
}
}

template<class U>
class Element
{
friend class Stack<U>;
Element *next;
U data;
Element(Element* n, int d) : next(n), data(d) {}
};

int main
{
Stack<int> s;
}


Many thanks!!

//Tony
 
V

Victor Bazarov

Tony said:
Assume I have the following template classes which are Stack and Element see
below.
I have removed all kinds of exeption just to get a shorter code.
The code below is not complete.

What do you mean by that?
I wonder if I could have something in main like
Stack<Element<T> > s;
because the stack contains of element of type Element.

It seems that in your design the fact that 'Stack' contains 'Element'
objects is _an_implementation_detail_, not something that should be
exposed to the user. You perhaps should look into making 'Element'
an inner class of 'Stack'.
Im I right.
Huh?

What changes should then has to be done in this present code.

To do what? Aside from the need to put parentheses after 'main' and
to define the 'empty' function in the Stack template, there is no need
to do anything to make your code compile.

Perhaps you should rethink your question.
template<class U>
class Element;

template <class T>
class Stack
{
public:
Stack() : first(0) {}
~Stack();
void push(T d);
void pop();
T top();
bool empty();

Need to define it...
private:
Element<T> *first;
Stack(const Stack&) {}
Stack& operator= (const Stack&) {}
};

template <class T>
void Stack<T>::push( T d)
{
first = new Element<T>(first, d);
}

template <class T>
Stack<T>::~Stack()
{
while(!empty() )
{
Element<T> *p = first;
first = first->next;
delete p;
}
}

template<class U>
class Element
{
friend class Stack<U>;
Element *next;
U data;
Element(Element* n, int d) : next(n), data(d) {}
};

int main

int main()
{
Stack<int> s;
}

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,150
Latest member
MakersCBDReviews
Top