码迷,mamicode.com
首页 > 其他好文 > 详细

类模板——stack类

时间:2016-04-21 21:58:49      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:


不能将模板类的声明与实现分开到.h和.cpp中写
类模板使用时必须将成员函数和实现写在一个头文件中,不能分开,不能分开,不能分开,重要的说三遍。

stack.h

 1 #ifndef STACK_H_
 2 #define STACK_H_
 3 template <class Type>
 4 class Stack
 5 {
 6 private:
 7     Type *ptr;
 8     int num;
 9     int size;
10 public:
11     Stack(const int &);
12     ~Stack(); 
13     void pop();
14     void push(const Type &a);
15     void output();
16 };
17 
18 
19 template <class Type>
20 Stack<Type>::Stack(const int &n)
21 {
22     ptr = new Type[n];
23     num = 0;
24     size = n;
25 }
26 
27 template <class Type>
28 Stack<Type>::~Stack()
29 {
30     delete[]ptr;
31 }
32 
33 template <class Type>
34 void Stack<Type>::pop()
35 {
36     if (num == 0)
37     {
38         cout << "Error! Stack is empty." << endl;
39         return;       //防止越界
40     }
41     ptr[num-1] = 0;
42     num--;         //计总数
43 }
44 
45 template <class Type>
46 void Stack<Type>::push(const Type &a)
47 {
48     if (num == size)
49     {
50         cout << "Error! Stack is full!." << endl;
51         return;      //防止越界
52     }
53     ptr[num] = a;
54     ++num;       //计总数
55 }
56 
57 template <class Type>
58 void Stack<Type>::output()
59 {
60     for (int i = 0; i < num; ++i)
61         cout << ptr[i];
62     cout << endl;
63 }
64 
65 #endif

mian.cpp

 1 #include<iostream>
 2 #include"Stack.h"
 3 using namespace std;
 4 int main()
 5 {
 6     Stack <int> a(10);
 7     for (int i = 1; i < 9; ++i)
 8         a.push(i);
 9     a.output();
10     a.pop();
11     a.output();
12     
13     Stack <char> b(10);
14     for (int i = 70; i < 76; ++i)
15         b.push(i);
16     b.output();
17 
18     system("pause");
19     return 0;
20 }

 

类模板——stack类

标签:

原文地址:http://www.cnblogs.com/-yixi/p/5418796.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!