在某些场景下,继承和包含并不总是能满足重用代码的需要。比如,容器类。容器类设计用来存储其他对象或数据类型。
比如如下的Stack类:
Stack.h
#ifndef STACK_H_
#define STACK_H_
#include <iostream>
using namespace std;
typedef unsigned long Type;
class Stack{
private:
enum {MAX = 10};
Type items[MAX];
int top;
public:
Stack();
bool isEmpty() const;
bool isFull() const;
bool push(const Type & item);
bool pop(Type & item);
};
#endif /* STACK_H_ */
Stack.cpp
#include "Stack.h"
Stack::Stack(){
top = 0;
}
bool Stack::isEmpty() const{
return top == 0;
}
bool Stack::isFull() const{
return top == MAX;
}
bool Stack:: push(const Type & item){
if (top < MAX){
items[top++] = item;
return true;
} else {
return false;
}
}
bool Stack::pop(Type & item){
if (top > 0){
item = items[--top];
return true;
} else {
return false;
}
}
上面的Stack类中只能存放unsigned long 类型,当需要存放其他类型时如果要重新写一个类,那未免太麻烦了。这种场景下,模板类就很实用了。
下面开始改造Stack类,使其成为一个模板类。使用模板定义替换Stack声明,使用模板成员函数替换Stack的成员函数。和模板函数一样,模板类采用如下开头:
template <typename Type>
在类声明和函数前添加模板声明:
Stack.h
#ifndef STACK_H_
#define STACK_H_
//typedef unsigned long Type;
template <class Type>
class Stack{
private:
enum {MAX = 10};
Type items[MAX];
int top;
public:
Stack();
bool isEmpty() ;
bool isFull() ;
bool push( Type item);
bool pop(Type & item);
};
#endif /* STACK_H_ */
Stack.cpp
#include "Stack.h"
#include <iostream>
using namespace std;
template <class Type>
Stack<Type>::Stack(){
top = 0;
}
template <class Type>
bool Stack<Type>::isEmpty() {
return top == 0;
}
template <class Type>
bool Stack<Type>::isFull() {
return top == MAX;
}
template <class Type>
bool Stack<Type>:: push( Type item){
if (top < MAX){
items[top++] = item;
return true;
} else {
return false;
}
}
template <class Type>
bool Stack<Type>::pop(Type & item){
if (top > 0){
item = items[--top];
return true;
} else {
return false;
}
}
int main(){
Stack<int> stack;
int num = 5;
stack.push(num);
return 0;
}