c++类模板初探

  1 #include <iostream>
  2 
  3 #include <string>
  4 
  5 using namespace std;
  6 
  7 // 你提交的代码将嵌入到这里
  8 
  9 const int SIZE = 100;
 10 
 11 template <class T>
 12 
 13 class Queue {
 14 
 15     T q[SIZE];
 16 
 17     int front;  //队列头
 18 
 19     int rear;   //队列尾
 20 
 21 public:
 22 
 23     Queue()
 24 
 25     {
 26 
 27         front = rear = 0;
 28 
 29     }
 30 
 31     void put(T i); 
 32 
 33     T get();  
 34 
 35 };
 36 
 37 
 38 
 39 template <class T>//注意在写成员函数的时候都要再次声明一下模板类
 40 
 41 void Queue<T>::put(T i)
 42 
 43 {
 44 
 45     rear++;
 46 
 47     q[rear] = i;
 48 
 49 }
 50 
 51 
 52 
 53 template<class T>
 54 
 55 T Queue<T>::get()
 56 
 57 {
 58 
 59     front++;
 60 
 61     return q[front];
 62 
 63 }
 64 
 65 int main()
 66 
 67 {
 68 
 69   Queue<int> a; // 创建一个整数队列
 70 
 71   int m,n;
 72 
 73   cin>>m>>n; 
 74 
 75   a.put(m);
 76 
 77   a.put(n);
 78 
 79   cout << a.get() << " ";
 80 
 81   cout << a.get() << endl;
 82 
 83 
 84 
 85   Queue<double> d; // 创建一个双精度浮点数队列
 86 
 87   double x,y;
 88 
 89   cin>>x>>y;
 90 
 91   d.put(x);
 92 
 93   d.put(y);
 94 
 95   cout << d.get() << " ";
 96 
 97   cout << d.get() << endl;
 98 
 99 
100 
101   Queue<string> qs;// 创建一个字符串队列
102 
103   string s1,s2,s3;
104 
105   cin>>s1>>s2>>s3;
106 
107   qs.put(s1);
108 
109   qs.put(s2);
110 
111   qs.put(s3);
112 
113   cout <<    qs.get() << " ";
114 
115   cout <<    qs.get() << " ";
116 
117   cout << qs.get() << endl;
118 
119 
120 
121   return 0;
122 
123 }

猜你喜欢

转载自www.cnblogs.com/cstdio1/p/10884962.html