CornedBee: The overloaded operator is in the same header file as the stack class.
Thantos: I tried that code, and it works fine, but for some reason mine doesn't. Here is the full stack header file:
Code:
#ifndef STACK_H
#define STACK_H
#include <assert.h>
#include <iostream>
using namespace std;
template <class ELEM, int LIST_SIZE = 10>
class Stack {
public:
Stack():size(LIST_SIZE)
{ clear(); }
~Stack()
{ }
void clear()
{ top = 0; }
void push(const ELEM& item)
{ assert(!isFull()); listarray[top++] = item; }
ELEM pop()
{ assert(!isEmpty()); return listarray[--top]; }
ELEM topValue() const
{ assert(!isEmpty()); return listarray[top-1]; }
bool isEmpty() const
{ return top == 0; }
bool isFull() const
{ return top == size; }
private:
const int size;
int top;
ELEM listarray[LIST_SIZE];
friend ostream & operator<<(ostream &disp, Stack<ELEM, LIST_SIZE> &rhs);
};
template <class T, int N = 10>
ostream & operator<< (ostream &disp, Stack<T, N> &rhs)
{
Stack<T, N> temp;
while (!rhs.isEmpty())
{
disp << rhs.topValue() << " ";
temp.push(rhs.pop());
}
while (!temp.isEmpty())
rhs.push(temp.pop());
return disp;
}
#endif
Note: Only the overloaded operator is my code, I am supposed to implement it.
Here is the driver that came with it:
Code:
#include <iostream>
using namespace std;
#include "stack.h"
main()
{
Stack<int> L1; //default size used
Stack<char, 6> L2; //override default size
char v = 'A';
cout << "Pushing to L2: ";
while(!L2.isFull()) {
cout << v << " ";
L2.push(v);
v += 1;
}
cout << "\nStack L2 is: top>>[" << L2 << "]" << endl;
cout << "Popping from L2 to L1: ";
while(!L2.isEmpty()) {
L1.push(L2.pop());
cout << L1.topValue() << " ";
}
cout << "\nL1's top: " << L1.topValue() << "\n";
cout << "Stack L1 is...." << L1 << endl;
L1.clear();
cout << "That is all.\n";
return 0;
}