#include<iostream>using namespace std;typedef int Datatype;class Stack
{
private:Datatype* items;//栈数组int stacksize;//栈的实际大小int top;//栈顶指针
public://构造函数:1)分配栈数组内存,2)把栈顶指针初始化为0;Stack(int size) :stacksize(size), top(0) {items = new Datatype [stacksize];}~Stack() {delete [] items;items = nullptr;}bool isempty()const {if (top == 0)return true;return false;}bool isfull()const {if (top == stacksize)return true;return false;}bool push(const Datatype& item) {//元素入栈;if (top < stacksize) {items[top++] = item; return true;}return false;}bool pop(Datatype &item){if (top > 0) { item = items[--top]; return true; }return false;}
};
int main()
{Stack ss(5);//元素入栈;ss.push(1); ss.push(2); ss.push(3); ss.push(4); ss.push(5);//元素chu栈;Datatype item;while (ss.isempty() == false) {ss.pop(item);cout << "item = " << item << endl;}return 0;
}
接下来我们把这个普通类改为模板类;
#include<iostream>using namespace std;template <class Datatype>
class Stack
{
private:Datatype* items;//栈数组int stacksize;//栈的实际大小int top;//栈顶指针
public://构造函数:1)分配栈数组内存,2)把栈顶指针初始化为0;Stack(int size) :stacksize(size), top(0) {items = new Datatype [stacksize];}~Stack() {delete [] items;items = nullptr;}bool isempty()const {if (top == 0)return true;return false;}bool isfull()const {if (top == stacksize)return true;return false;}bool push(const Datatype& item) {//元素入栈;if (top < stacksize) {items[top++] = item; return true;}return false;}bool pop(Datatype &item){if (top > 0) { item = items[--top]; return true; }return false;}
};
int main()
{Stack<int>ss(5);//元素入栈;ss.push(1); ss.push(2); ss.push(3); ss.push(4); ss.push(5);//元素chu栈;int item;while (ss.isempty() == false) {ss.pop(item);cout << "item = " << item << endl;}return 0;
}
创建模板类的方法:
先写一个普通类,用具体的数据类型。
调试普通类。
把普通类改为模板类;