Stack.h文件如下所示:
#pragma once
#include<string>
#include<exception>
template<typename T>
class Stack
{
private:
T *elementData;
int capacity;
int top;
public:
Stack(int capacity);
~Stack(void);
int Size();
bool IsEmpty();
void Push(T c);
T Pop();
T Peek();
void Clear();
class Stack_error : public std::runtime_error {
public:
Stack_error(const std::string &str) : std::runtime_error(str){}
};
};
template<typename T>
Stack<T>::Stack(int capacity)
{
if(capacity<1) throw Stack_error("capacity is less than 1");
this->capacity = capacity;
this->elementData = new T[capacity];
this->top = -1;
}
template<typename T>
Stack<T>::~Stack(void)
{
}
template<typename T>
int Stack<T>::Size() {
return top + 1;
}
template<typename T>
bool Stack<T>::IsEmpty() {
return top == -1;
}
template<typename T>
void Stack<T>::Push(T c) {
if(top==capacity-1) throw Stack_error("Stack is Full");
elementData[++top] = c;
}
template<typename T>
T Stack<T>::Pop() {
if(IsEmpty()) throw Stack_error("Stack is Empty");
return elementData[top--];
}
template<typename T>
T Stack<T>::Peek() {
if(IsEmpty()) throw Stack_error("Stack is Empty");
return elementData[top];
}
template<typename T>
void Stack<T>::Clear() {
top = -1;
}
注意事项:template<nametype T>中的nametype可以换成class。成员函数的定义需要跟声明放在一个文件里面,而不是像其他类定义中可以将声明放在.h文件,而将定义放在.cpp文件里面,如果分开放的话会报找不到定义的错误。
上述代码中,函数的定义都需要在最前面带上template<typename T>,并且::之前不能只写类名Stack,而需要同时带上类型参数名,即Stack<T>
也可以像下面这样在声明的时候同时给出定义,注意与上面代码之间的区别:
#pragma once
#include<string>
#include<exception>
template<typename T>
class Stack
{
private:
T *elementData;
int capacity;
int top;
public:
Stack(int capacity)
{
if(capacity<1) throw Stack_error("capacity is less than 1");
this->capacity = capacity;
this->elementData = new T[capacity];
this->top = -1;
}
~Stack(void){}
int Size(){return top + 1;}
bool IsEmpty(){return top == -1;}
void Push(T c){
if(top==capacity-1) throw Stack_error("Stack is Full");
elementData[++top] = c;
}
T Pop(){
if(IsEmpty()) throw Stack_error("Stack is Empty");
return elementData[top--];
}
T Peek() {
if(IsEmpty()) throw Stack_error("Stack is Empty");
return elementData[top];
}
void Clear(){top = -1;}
class Stack_error : public std::runtime_error {
public:
Stack_error(const std::string &str) : std::runtime_error(str){}
};
};
上面的代码就不需要在每个成员函数之前都加上template<nametype T>
最后是使用模板的代码:
#include <iostream>
#include <string>
#include "Stack.h"
using namespace std;
int main() {
try{
Stack<string> stack(5);
stack.Push("aaa");
stack.Push("bbb");
stack.Push("ccc");
cout << stack.Pop() << endl;
cout << stack.Pop() << endl;
cout << stack.Pop() << endl;
}catch(const Stack<string>::Stack_error &e) {
cerr << e.what() << endl;
}
try{
Stack<char> stack(5);
stack.Push('a');
stack.Push('b');
stack.Push('c');
cout << stack.Pop() << endl;
cout << stack.Pop() << endl;
cout << stack.Pop() << endl;
}catch(const Stack<char>::Stack_error &e) {
cerr << e.what() << endl;
}
}
水平有限,如有不当之处,还望指正!