Advertisement
gha890826

stake made by template

May 27th, 2019
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. // ConsoleApplication2.cpp : 定義主控台應用程式的進入點。
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6. using namespace std;
  7.  
  8. template < class T, int maxsize = 20>
  9. class stake
  10. {
  11. public:
  12.     stake(){ sp = 0; }
  13.     void push(T data);
  14.     T pop();
  15. private:
  16.     int sp;
  17.     T buffer[maxsize];
  18.     static void error(){ cout << "\nstake error\n"; }
  19. };
  20.  
  21. template<class T,int maxsize>
  22. void stake<T, maxsize>::push(T data)
  23. {
  24.     if (sp == maxsize)
  25.         error();
  26.     else
  27.     {
  28.         buffer[sp++] = data;
  29.     }
  30. }
  31.  
  32. template<class T,int maxsize>
  33. T stake<T, maxsize>::pop()
  34. {
  35.     if (sp == 0)
  36.     {
  37.         error();
  38.         return 0;
  39.     }
  40.     else
  41.     {
  42.         cout << buffer[--sp];
  43.     }
  44. }
  45.  
  46.  
  47. int main()
  48. {
  49.     stake<int> st1;
  50.     stake<char, 10> st2;
  51.    
  52.     st1.push(1);
  53.     st1.push(2);
  54.     st1.push(3);
  55.  
  56.     st2.push('a');
  57.     st2.push('b');
  58.     st2.push('c');
  59.  
  60.     st1.pop();
  61.     st2.pop();
  62.     st1.pop();
  63.     st2.pop();
  64.     st1.pop();
  65.     st2.pop();
  66.     st2.pop();
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement