I searched for similar questions, but could not find one that I could apply to my situation. I have a stack class using an array class as a data member. I test it with push and pop in 'main()' on a stack of size 5 (in this case, data member 'Array m_array'). I use a for loop to fill the stack with postfix incrementation, but instead of pushing 0 into the first element, it pushes 1. My output is:
1
2
3
4
3
2
1
0
-1
Stack is full(empty)
But I want it to be
0
1
2
3...
In test:
int main()
{
try {
Stack<int> s(5);
for (int i = 0; i < 4; i++) {
s.Push(i);
cout << s << endl;
}
cout << endl;
for (int i = 0; i < 8; ++i) {
s.Pop();
cout << s << endl;
}
}
catch (ArrayException &ex) //catch object
{
cout << ex.GetMessage() << endl;
}
catch(...) //default catch
{
cout << "An unhandled exception has occurred" << endl;
}
return 0;
}
In stack.cpp:
#ifndef STACK_CPP
#define STACK_CPP
#include "stack.h"
namespace Jules
{
namespace Containers
{
template<typename T> //default constructor
Stack<T>::Stack() : m_array(Array<T>()), m_current(0)
{
}
template<typename T> //destructor
Stack<T>::~Stack()
{
}
template<typename T> //copy constructor
Stack<T>::Stack(const Stack<T> &s) : m_array(s.m_array), m_current(s.m_current)
{
}
template<typename T> //constructor with input argument
Stack<T>::Stack(const int i) : m_array(i), m_current(0)
{
}
template<typename T> //assignment operator
Stack<T> Stack<T>::operator=(Stack<T> const &source)
{
if (this == &source)
return *this;
Stack<T>::operator = (source);
return *this;
}
template<typename T> //push function
void Stack<T>::Push(const T& element)
{
m_array[m_current] = element;
++m_current;
}
template<typename T> //pop function
void Stack<T>::Pop()
{
--m_current;
m_array[m_current];
}
template<typename T2> //send to ostream
ostream& operator << (ostream& os, const Stack<T2>& t)
{
os << t.m_current;
return os;
}
}
}
#endif