Ex8_A.cpp
上传用户:wuzhousb
上传日期:2022-07-12
资源大小:380k
文件大小:1k
源码类别:

书籍源码

开发平台:

Visual C++

  1. /*由数组类模板的实例派生栈类模板。*/
  2. #include<iostream>
  3. using namespace std;
  4. template<class T,int size> class array{
  5. T a[size];
  6. int last;
  7. int maxSize;
  8. public:
  9. array(){last=-1;maxSize=size;}
  10. bool isfull(){if(last==maxSize-1) return true; else return false;}
  11.     bool isempty(){if(last==-1) return true; else return false;}
  12. void insertRear(T data){        //将data插在数组最后一个元素位置,可用于创建数组
  13. if(!isfull()) a[++last]=data;
  14. else cout<<"array is full,can not insert!"<<endl;
  15. }
  16. T deleteRear(){      //将数组最后一个元素从数组中删除,值返回
  17. if(!isempty()){
  18. return a[last--];
  19. }
  20. else cout<<"array is empty,can not delete!"<<endl;
  21. }
  22. void print(){        //输出数组
  23. for(int i=0;i<=last;i++) cout<<a[i]<<'t';
  24. cout<<endl;
  25. }
  26. //其他无关接口函数略
  27. };
  28. template<class T,int size> class stack:private array<T,size>{//私有派生屏蔽原有的接口函数
  29. public:
  30. void push(T data){
  31. insertRear(data);
  32. }
  33. T pop(){
  34. return deleteRear();
  35. }
  36. void stackprint(){print();}
  37. };
  38. int main(){
  39. stack<int,9> istack;
  40. int m,i;
  41. cout<<"请输入9个整数:"<<endl;
  42. for(i=0;i<9;i++){         //创建数组
  43. cin>>m;
  44.         istack.push(m);
  45. }
  46. istack.stackprint();    
  47. for(i=0;i<9;i++){         //创建数组
  48.         cout<<istack.pop()<<'t';
  49. }   //排序
  50. istack.stackprint();
  51. return 0;
  52. }