Ex8_A.cpp
上传用户:wuzhousb
上传日期:2022-07-12
资源大小:380k
文件大小:1k
- /*由数组类模板的实例派生栈类模板。*/
- #include<iostream>
- using namespace std;
- template<class T,int size> class array{
- T a[size];
- int last;
- int maxSize;
- public:
- array(){last=-1;maxSize=size;}
- bool isfull(){if(last==maxSize-1) return true; else return false;}
- bool isempty(){if(last==-1) return true; else return false;}
- void insertRear(T data){ //将data插在数组最后一个元素位置,可用于创建数组
- if(!isfull()) a[++last]=data;
- else cout<<"array is full,can not insert!"<<endl;
- }
- T deleteRear(){ //将数组最后一个元素从数组中删除,值返回
- if(!isempty()){
- return a[last--];
- }
- else cout<<"array is empty,can not delete!"<<endl;
- }
- void print(){ //输出数组
- for(int i=0;i<=last;i++) cout<<a[i]<<'t';
- cout<<endl;
- }
- //其他无关接口函数略
- };
- template<class T,int size> class stack:private array<T,size>{//私有派生屏蔽原有的接口函数
- public:
- void push(T data){
- insertRear(data);
- }
- T pop(){
- return deleteRear();
- }
- void stackprint(){print();}
- };
- int main(){
- stack<int,9> istack;
- int m,i;
- cout<<"请输入9个整数:"<<endl;
- for(i=0;i<9;i++){ //创建数组
- cin>>m;
- istack.push(m);
- }
- istack.stackprint();
- for(i=0;i<9;i++){ //创建数组
- cout<<istack.pop()<<'t';
- } //排序
- istack.stackprint();
- return 0;
- }