首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

linux上练习 c++ 栈中使用类模版例子

2012-10-21 
linux下练习 c++栈中使用类模版例子//栈中使用类模版例子#include iostream#include typeinfousing na

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;}

linux上练习 c++  栈中使用类模版例子


 

热点排行