C++模板
模板是C++最有特色的语法,也是最复杂的语法。它将类型看作一种参数来进行编程。
1. 模板函数
写一个max,求两个东西中较大的一个。
它们的算法都是类似的,只是参与运算的对象的类型不同。我们可以把类型定义成一个参数:
调用方法
调用时会自动对模板函数的类型进行推导。前面这个模板还不能对两个C字符串进行比较,比如
可以对函数进行重载
2. 模板类
1 class Stack {
2 int *data_;
3 int size_;
4 int capacity_;
5 public:
6 Stack(int capacity) {
7 capacity_ = capacity;
8 size_ = 0;
9 data_ = new int[capacity_];
10 }
11 ~Stack() {
12 delete[] data_;
13 }
14 void push(int t) {
15 data_[size_++] = t;
16 }
17 void pop() {
18 size_--;
19 }
20 int top() const{
21 return data_[size_-1];
22 }
23 bool empty() const{
24 return size_ == 0;
25 }
26 int size() const {
27 return size_;
28 }
29 };
这个栈只能用来存放int不能存放其他东西,为了让他能够存放其他东西,我们把int参数化
1 template<class T>
2 class Stack {
3 T *data_;
4 int size_;
5 int capacity_;
6 public:
7 Stack(int capacity) {
8 capacity_ = capacity;
9 size_ = 0;
10 data_ = new T[capacity_];
11 }
12 ~Stack() {
13 delete[] data_;
14 }
15 void push(const T &t) {
16 data_[size_++] = t;
17 }
18 void pop() {
19 size_--;
20 }
21 T top() const{
22 return data_[size_-1];
23 }
24 bool empty() const{
25 return size_ == 0;
26 }
27 int size() const {
28 return size_;
29 }
30 };
有了这个模板类以后,我们可以定义存放各种类型元素的栈: