C++模板栈实现与异常处理

📅 2026/7/10 14:00:05 👤 编程新知 🏷️ 技术资讯
C++模板栈实现与异常处理 #include iostream #define MAX 7 using namespace std; template typename T class Stack { T top;//栈顶 T data[MAX];// public: Stack():top(-1),data{0}{} void stackpush(T s); void stackpop(); bool empty(); bool full(); void show(); }; template typename T bool StackT::empty() { return top-1?1:0; } template typename T bool StackT::full() { return topMAX-1?1:0; } template typename T void StackT::stackpush(T s) { if(full()) { cout 满栈 endl; return; } this-top; data[top]s; cout data[top] 入栈 endl; return; } template typename T void StackT::show() { if(empty()) { cout 空栈 endl; return; } for(int itop;i0;i--) { cout data[i] ; } cout endl; } template typename T void StackT::stackpop() { this-top--; cout data[top] 出栈 endl; } int main() { Stack ints; s.show(); s.stackpush(10); s.stackpush(9); s.stackpush(8); s.stackpush(7); s.stackpush(6); s.stackpush(5); s.stackpush(4); s.stackpush(3); s.stackpop(); s.stackpop(); s.stackpop(); s.stackpop(); s.show(); return 0; }#include iostream using namespace std; template typename T,typename T1 T fun(T a,T1 b) { if(b0) { throw int(0); } if(b10) { throw int(10); } if(sizeof(b)!4) { throw double(1); } return a/b; } int main() { try { // fun(88,0); // fun(55,10); funint,double(99,99.9); } catch (int re) { if(re0) cout b0异常 endl; if(re10) cout b10异常 endl; } catch (double) { cout b1异常 endl; } cout Hello World! endl; return 0; }