在上一关中,我们构造了 Stack 类的第一个版本。事实上,在上一关的实现中,Stack::init(unsigned int) 与 Stack::cleanup() 分别起到了初始化成员对象与销毁成员对象的作用。
class Stack{
public:
Stack();
Stack (unsigned int);
Stack (const Stack&)
~Stack();
public:
bool pop(); // 弹栈操作
bool push(int); // 压栈操作
int readTop(); // 读栈顶元素
bool isEmpty(); // 判断栈是否为空
private:
int * data; // 存储栈数据的数组
unsigned int top; // 栈顶元素下标
unsigned int size; // 栈的最大容量
public:
static unsigned int objNum;
static unsigned int defSize;
} ;
#include <iostream>
#include <cstring>
using namespace std;
class Stack {
public:
Stack();
Stack(unsigned int);
Stack(const Stack&);
~Stack();
public:
bool pop();
bool push(int);
int readTop();
bool isEmpty();
private:
int* data;
unsigned int top;
unsigned int size;
public:
static unsigned int objNum;
static unsigned int defSize;
};
unsigned int Stack::objNum = 0;
unsigned int Stack::defSize = 20;
/************* begin **************/
Stack::Stack()
{
this->size = this->defSize;
this->data = new int[this->size];
this->top = 0;
}
Stack::Stack(unsigned int sz)
{
this->size = sz;
this->data = new int[this->size];
this->top = 0;
}
Stack::Stack(const Stack& st)
{
this->size = st.size;
this->top = st.top;
this->data = new int[this->size];
memcpy(this->data, st.data, st.size * 4);
}
Stack::~Stack()
{
delete[] this->data;
this->size = 0;
this->top = 0;
}
bool Stack::pop()
{
if (this->top == 0) return false;
this->top--;
return true;
}
bool Stack::push(int k)
{
if (this->top == this->size) return false;
this->data[this->top] = k;
this->top++;
return true;
}
int Stack::readTop()
{
return this->data[this->top - 1];
}
bool Stack::isEmpty()
{
return this->top == 0;
}
/************* end **************/
#define N 10
int main(int argc, char** argv) {
Stack s(N + 1);
int v;
for (int i = 0; i < N; i++) {
cin >> v;
s.push(v);
}
for (int i = 0; i < N; i++) {
cout << s.readTop() << endl;
s.pop();
}
return 0;
}