第一次写博客,本系列主要记录下C++学习过程中编写的代码以及遇到的一些问题
#include <iostream>
using std::cout;
using std::endl;
class Stack
{
public:
Stack(const int stacksize);
Stack(const Stack & rhs);
Stack & operator=(const Stack & rhs);
~Stack();
void push(const int & x);
void pop();
bool empty();
bool full();
int top();
private:
int _stacksize;
int *_base;
int *_top;
};
Stack::Stack(const int stacksize)
: _stacksize(stacksize)
, _base(new int[stacksize]())
, _top(_base-1)
{}
Stack::Stack(const Stack & rhs)
: _stacksize(rhs._stacksize)
, _base(new int[_stacksize]())
, _top(_base-1)
{}
Stack & Stack::operator=(const Stack & rhs)
{
if(this != &rhs)
{
delete [] _base;
_base = new int[rhs._stacksize]();
_top = _base - 1;
}
return *this;
}
Stack::~Stack()
{
delete [] _base;
cout << "~Stack()" << endl;
}
void Stack::push(const int & x)
{
if((_top - _base) <= (_stacksize-1))
{
++(_top);
*_top = x;
}else
{
cout << "Stack is full" << endl;
}
}
void Stack::pop()
{
if((_top - _base) >= 0)
{
--_top;
}else
{
cout << "Stack is empty" << endl;
}
}
bool Stack::full()
{
if((_top - _base) >= (_stacksize-1))
return true;
else
return false;
}
bool Stack::empty()
{
if((_top - _base) <= -1)
return true;
else
return false;
}
int Stack::top()
{
return *_top;
}
void test0()
{
Stack S(10);
for(int i = 0; i < 15; ++i)
{
if(!S.full())
{
S.push(i);
}
else
{
cout << "full, i = " << i << endl;
break;
}
}
for(int i = 0; i < 15; ++i)
{
if(!S.empty())
{
cout << "the " << i << " top element is " << S.top() << endl;
S.pop();
}
else
{
cout << "empty, i = " << i << endl;
break;
}
}
}
int main(void)
{
test0();
return 0;
}