用Type代替所有int类型
不用类模板的代码:
不用类模板的子函数:
用类模板的子函数:
使用类模板修改后的栈基本操作代码:
/*main.cpp文件*/
#include "Stack.h"
/*类模板不带异常捕获*/
int main(){
CharStack s1(2);//定义一一个字符型的堆栈
DoubleStack s2(2);//在定义一个double型堆栈
char ch;
double d;
s1.push('a');
s1.push('b');
ch=s1.pop();
cout<<ch<<endl;
ch = s1.pop();
cout <<ch<<endl;
s2.push(2.1);
s2.push(3.0);
d=s2.pop();
cout <<d <<endl;
d=s2.pop();
cout << d <<endl;
}
/*Stack.h文件*/
#ifndef STACK_H
#define STACK_H
const int MAX_SIZE=100;
template<class DataType>
class stack
{
privata:
DataType *data;
int size;
int top;
public:
Stack();
Stack(int s);//这个是数组长度,i、必须用int
~Stack();
//void push(char ch);
void push(DataType n);
//char pop();
DataType pop();
//char getTop();
DataType getTop();
bool isEmpty();
bool isFull();
void setNull();
void reverseDisplay();
DataType* getData();
int getLength();
};
//为保证模板类可以正常使用
//需要在源文件的末尾加上
typedef Stack<char> CharStack;
typedef Stack<int> IntStack;
typedef Stack<double> DoubleStack;
#endif
/*Stack.cpp文件*/
#include "Stack.h"
#include <iostream>
using namespace std;
templata<class DataType>
Stack<DataType>::Stack(){
top = -1;
size = MAX_SIZE;
data = new DataType[size];
}
templata<class DataType>
Stack<DataType>::Stack(int s){
size = s;
top = -1;
data = new DataType[size];
}
templata<class DataType>
Stack<DataType>::~Stack(){}
//以此类推,等等子函数
//在.cpp文件中显示。需要声明
typedef class Stack<char> ;
typedef class Stack<int> ;
typedef class Stack<double> ;