C++模板詳解(一)
阿新 • • 發佈:2018-12-29
1 #include <iostream>
2 #include <string>
3 #include <stdexcept> //std::out_of_range
4 #include <cstdlib> //EXIT_FAILURE
5 using namespace std;
6
7 /*********模板類,宣告開始,一般都是放在標頭檔案的*********/
8
9 template<class T, int MAXSIZE>
10 class myStack
11 {
12 public:
13 myStack();
14 void push(T const &); //入棧
15 void pop(); //出棧
16 T top() const; //返回棧頂
17
18 bool empty() const //判斷是否為空
19 {
20 return size == 0;
21 }
22
23 bool full() const //判斷棧是否已滿
24 {
25 return size == MAXSIZE;
26 }
27
28 private:
29 T elems[MAXSIZE]; //使用陣列存放棧元素,由於非型別形參MAXSIZE在類內是一個常量,所以可以用來宣告陣列大小
30 int size; //棧已使用空間
31 };
32
33 /**********模板類,宣告結束,定義成員函式開始********/
34
35 template<class T, int MAXSIZE>
36 myStack<T, MAXSIZE>::myStack(): size(0) //建構函式,初始化為空
37 {
38 }
39
40 template<class T, int MAXSIZE>
41 void myStack<T, MAXSIZE>::push(T const &new_elem) //入棧
42 {
43 if(size == MAXSIZE)
44 {
45 throw out_of_range("myStack::push(): stack is full");
46 }
47 elems[size++] = new_elem;
48 }
49
50 template<class T, int MAXSIZE>
51 void myStack<T, MAXSIZE>::pop() //棧頂出棧
52 {
53 if(size <= 0)
54 {
55 throw out_of_range("myStack::pop(): stack is empty");
56 }
57 --size;
58 }
59
60 template<class T, int MAXSIZE>
61 T myStack<T, MAXSIZE>::top() const //返回棧頂元素
62 {
63 if(size <= 0)
64 {
65 throw out_of_range("myStack::top(): stack is empty");
66 }
67 return elems[size - 1];
68 }
69
70 /***********成員函式定義結束**********************/
71
72 int main(int argc, char *argv[])
73 {
74 try
75 {
76 myStack<int, 20> int20Stack;
77 myStack<int, 40> int40Stack;
78 myStack<string, 40> stringStack;
79
80 int20Stack.push(7);
81 cout << int20Stack.top() << endl; //輸出7
82 int20Stack.pop();
83
84 for(int i = 0; i < 40; ++i)
85 int40Stack.push(i);
86 cout << int40Stack.top() << endl; //輸出39
87 //int40Stack.push(41); //繼續新增元素,會丟擲異常,輸出Exception: myStack::push(): stack is full
88
89 stringStack.push("hello");
90 cout << stringStack.top() << endl; //輸出hello
91 stringStack.pop();
92 //stringStack.pop(); //繼續出棧,會丟擲異常,輸出Exception: myStack::push(): stack is empty
93
94 return 0;
95 }
96 catch(out_of_range const &ex)
97 {
98 cerr << "Exception: " << ex.what() << endl;
99 return EXIT_FAILURE;
100 }
101 }