抽象数据类型(abstract data type, ADT)以通用的方式描述数据类型。C++中类的概念非常适合于ADT方法。例如,C++程序通过堆栈来管理自动变量,堆栈可由对它执行的操作来描述。
- 可创建空堆栈;
- 可将数据项添加到堆顶(压入);
- 可从栈顶删除数据项(弹出);
- 可查看堆栈是否填满;
- 可查看堆栈是否为空;
可将上述描述转换为一个类声明,其中公有成员函数提供了表示堆栈操作的接口,私有数据成员负责存储堆栈数据。类声明头文件stack.h代码如下:
#pragma once
#ifndef STACK_H_
#define STACK_H_
typedef unsigned short Item;
class stack
{
private:enum {MAX=10};///stack类作用域中的常量Item items[MAX];int top;
public:stack();bool isempty() const;bool isfull() const;bool push(const Item& item);bool pop(const Item& item);
};
#endif // !STACK_H_
对应的源码文件代码如下:
#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;top = top + 1;return true;}else{return false;}
}
bool stack::pop(Item& item)
{if (top > 0){top = top - 1;item = items[top];return true;}else{return false;}
}
程序说明:
- 程序通过创建一个独立的数组来表示堆栈,并使用枚举创建了一个符号常量来表示堆栈的大小。
- 构造函数表示创建的堆栈为空,索引值为0;
- isempty()和isfull()函数用来判断堆栈是否为空或堆栈是否已满,通过索引值来判断即可;
- push()函数表示将一个数据压入堆栈,将数据压入堆栈后,索引值随之改变,如返回true,则表示数据成功压入堆顶。
- pop()函数表示将一个数据弹出堆栈,弹出的数据通过函数参数返回出来,同时索引值相应的减一,如返回值为true,则表示数据弹出成功。
- 头文件使用typedef用Item来表示unsigned short,如果需要double或结构类型的堆栈,只需修改typedef语句即可,类声明和方法定义保持不变。