c++学习:一个简单的类

/*************************************************
 * 栈                                            *
 *    实现简单stack类的栈                        *
 *************************************************/
#include<iostream>
#include<cstdlib>
#include<assert.h>
using namespace std;
const int STACK_SIZE = 100; //the max size of this stack;
/**************************************************
 * stack 类                                       *
 * 成员函数                                       *
 *  init ——初始化栈                             *
 *  push -- 在栈中放入一个元素                    *
 *  pop  -- 弹出栈中顶部元素                      *
 **************************************************/

class stack {
private:
 int count; //elememt of this stack;
 int data[STACK_SIZE]; //元素本身
public:
 //初始化栈
 void init();
 //将一个元素压到栈中
 void push(const int item);
 //从栈中弹出一个元素
 int pop();
};
/*************************************************
 *stack::init--初始化栈                          *
 *************************************************/

inline void stack::init()
{
 count = 0;//栈清零
}
/**************************************************
 * stack::push --将一个元素压到栈中;             *
 * 警告:这里没有检查栈时候溢出                   *
 * 入口参数                                       *
 * item:要放入的元素                              *
 **************************************************/

inline void stack::push(const int item)
{
 assert((count >= 0)&&
      (count < sizeof (data)/sizeof (data[0])));
 data[count] = item;
 ++count;
}
/*************************************************
 * stack::pop --将一个元素从栈中弹出             *
 *警告:这里没有检查栈是否溢出                   *
 *返回                                           *
 *栈的顶部元素                                   *
 *************************************************/
inline int stack::pop()
{
 //栈下一位
 count--;
 return (data[count]);
}

//简单测试
void main()
{
 stack  a_stack;//准备使用栈

    a_stack.init();

 a_stack.push(1);
 a_stack.push(2);
 a_stack.push(3);

 cout<< "expect a 3:"<<a_stack.pop() <<"/n";
 cout<< "expect a 2:"<<a_stack.pop() <<"/n";
 cout<< "expect a 1:"<<a_stack.pop() << "/n";
 
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值