/*头文件stack.h*/
#ifndef STACK_H_
#define STACK_H_
typedef unsigned long Item;
class Stack
{
public:
Stack();
bool isempty()const;
bool isfull()const;
bool push(const Item & item);
bool pop(Item & item);
private:
enum {MAX = 100};
Item items[MAX];
int top;
};
#endif
/*实现文件main.cpp*/
#include"stack.h"
Stack::Stack()
{
top = 0;
}
bool Stack::isempty() const
{
return top == 0;
}
bool Stack::isfull() const
{
return top == MAX;
}
bool Stack::push(const Item& item)
{
if (top < MAX)
{
items[top++] = item;
return true;
}
else
return false;
}
bool Stack::pop(Item& item)
{
if (top > 0)
{
item = items[--top];
return true;
}
else
return false;
}
这是从C++ primer上看到的一个可以表现堆栈工作原理的一个类,从中可以知道在堆栈中从顶端删除元素只是将该元素从被标记变为不被标记,并未删除改元素。然后当加入新的元素时便可以使用该内存,新的值将原来的值覆盖掉。有时候我们定义一个变量,未对其初始化,但却可以输出值,很可能就是以前这个内存地址已经被使用过,那么以前的值也就保存在这了。所以我们在使用一个变量前一定要记得将其初始化哦^_^...^_^...
737

被折叠的 条评论
为什么被折叠?



