linux下练习 c++ 栈中使用类模版例子
//栈中使用类模版例子 #include <iostream> #include <typeinfo> using namespace std; //typedef char T; template<typename T,int len=4>//可以有默认值,有默认值的参数靠右 //如果成员函数在类外写,那么每个函数前要加语句: template<typename T> class Stack { T a[len]; int cur; public: Stack():cur(0){} const char* stype()const//类型 { return typeid(T).name(); } int max_size()const//最大空间 { return len; } void push(const T& d) throw(const char*)//入栈 { if(full()) throw "满"; a[cur++]=d; } T pop() throw (const char*)//出栈 { if(empty()) throw "空"; return a[--cur]; } const T& top() const throw(const char*)//取顶元素 { if(empty()) throw "空"; return a[cur-1]; } bool empty()const//是否空 { return cur==0; } bool full()const//是否满 { return cur==len; } void clear()//清空 { cur=0; } void travel()//遍历 { while(!empty()) { cout<<pop()<<' '; } cout<<endl; } int size()const{return cur;}//元素个数 }; int main() { Stack<char,10> s; Stack<int> d; s.push('+');s.push('-');s.push('*');s.push('/'); d.push(123); d.push(42); d.push(666); cout<<s.stype()<<endl; s.travel(); cout<<d.stype()<<endl; d.travel(); return 0; }