【类和对象】第2关:构造方法与析构方法:Stack 类的第二个版本

在上一关中,我们构造了 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;
}
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值