类模板
类模板:
Template <typename T>
声明模板T只对下面一个类有效,因此函数的声明与实现必须在类中完成。
Stack<string> s;
类的调用
把模板的未定类型确定下来,成为模板的实例化。
#include <iostream>
#include <string>
using namespace std;
//形参默认值
template <typename T = int, int size = 5>
class Stack{
T a[size];
int cur;
public:
Stack():cur(0){}
//数据入栈成为栈顶
Stack& push(const T& d)throw(const char*){
if (full()) {
throw "man le"; }
a[cur++] = d;
return *this;
}
//栈顶数据出栈,下一个数据成为栈顶
T pop()throw(const char*){
if (empty()){
throw "kong le";}
return a[--cur];
}
//取出栈顶数据
const T&top()const;
//是否空栈
bool empty()const{
return cur==0;
}
//是否已满
bool full()const{
return cur==5;
}
//栈清空(复位 )
void clear(){
cur=0;
}
//栈中数据个数
int size()const{
return cur;
}
};
template <typename T, int size>
const T& Stack<T, size>::top()const{
if (empty()){
throw "kong le";}
return a[cur-1];
}
特例化
//template <int size>
//class Stack<const char*, size>{
// string a[size];
// int cur;
//public:
// Stack():cur(0){}
//
// //数据入栈成为栈顶
// Stack& push(const string& d)throw(const char*){
// if (full()) {
// throw "man le"; }
// a[cur++] = d;
// return *this;
// }
//
// //栈顶数据出栈,下一个数据成为栈顶
// string pop()throw(const char*){
// if (empty()){
// throw "kong le";}
// return a[--cur];
// }
//
// //取出栈顶数据
// const string&top()const;
//
// //是否空栈
// bool empty()const{
// return cur==0;
// }
//
// //是否已满
// bool full()const{
// return cur==5;
// }
//
// //栈清空(复位 )
// void clear(){
// cur=0;
// }
//
// //栈中数据个数
// int size()const{
// return cur;
// }
//
//};
int main (){
Stack<string, 7> s;
s.push("1").push("2").push("3").push("4").push("5");
while(!s.empty()){
cout << s.pop() << endl;
}
cout << "=============================================" << endl;
char buf[100];
/*
这里需要注意,会出现都是 end 的情况。
原因:const char * 其实是保存的地址,因此栈中每次存的数据都一样,为buf数组的首地址
所以最后一次输入 end 后,循环输出时每次调出的结果都是 end
解决:特例化,对比特例化注释前后的变化
*/
Stack<const char *> ss;
for (;;){
cin >> buf;
if(strcmp(buf, "end")==0){
break;
}
cout << "-------" << endl;
//cout << buf << endl;
ss.push(buf);
cout << "-------" << endl;
}
cout << "=============================================" << endl;
while(!ss.empty()){
cout << ss.pop() << endl;
}
cin.ignore();
getchar();
return 0;
}