栈类模板的使用
//文件opk.h
//声明类模板
#ifndef opk_h#define opk_h#include<iostream>#include<string>using namespace std;template<class TYPE>class Stack1{public:Stack1(int=10);~Stack1(){delete []stackptr;}int push(const TYPE&);int pop(TYPE&);int isFull() const{return top==size-1;}int isEmpty() const{return top==-1;}private:int size;int top;TYPE* stackptr;};#endif
//#ifndef opk_h
//#define opk_h
//............................
//#endif
//以上几行保证声明模板类的唯一性
防止以下之类的错误

//文件opk.cpp
#include"opk.h"template<class TYPE>Stack1<TYPE>::Stack1(int a){size=a>0&&a<1000?a:10;top=-1;stackptr=new TYPE[size];}template<class TYPE>int Stack1<TYPE>::push(const TYPE& item){if(!isFull()){stackptr[++top]=item;return 1;}return 0;}template<class TYPE>int Stack1<TYPE>::pop(TYPE& popvalue){if(!isEmpty()){popvalue=stackptr[top--];return 1;}return 0;}#include"opk.h"#include<iostream>using namespace std;int main(){Stack1<char> charstack;char c='a';cout<<"pushing elements onto charstack "<<endl; while(charstack.push(c)){cout<<c<<" ";c+=1;}cout<<endl<<"Stack is full.cannot push "<<c<<endl;cout<<"poping elements from charstack "<<endl;while(charstack.pop(c))cout<<c<<" ";cout<<endl<<"Stack is empty. cannot pop "<<endl;Stack1<double> doublestack(5);double f=1.1;cout<<"pushing elements onto doublestack "<<endl;while(doublestack.push(f)){cout<<f<<" ";f+=1.1;}cout<<endl<<"Stack is full. cannot push "<<f<<endl;cout<<"poping elements from doublestack "<<endl;while(doublestack.pop(f))cout<<f<<" ";cout<<endl<<"Stack is empty. cannot pop "<<endl;Stack1<int> intstack;int i=1;cout<<"pushing elements onto intstack "<<endl;while(intstack.push(i)){cout<<i<<" ";i+=1;}cout<<endl<<"Stack is full. cannot push "<<f<<endl;cout<<"poping elements from intstack "<<endl;while(intstack.pop(i))cout<<i<<" ";cout<<endl<<"Stack is empty. cannot pop "<<endl;system("pause");return 0;}
- 1楼zh63445528338分钟前
- 顶一个,不够。