1 //异常处理的过程主要有三个步骤 2 //抛出异常、捕捉异常和处理异常 3 #include<iostream.h> 4 5 class PushOnFull{ 6 }; 7 8 class PopOnEmpty{ 9 }; 10 11 class SeqStack{ 12 private: 13 int *data; 14 int MaxStackSize; 15 int top; 16 public: 17 SeqStack(int n); 18 ~SeqStack(); 19 20 void Push(const int item); 21 int Pop(); 22 }; 23 24 SeqStack::SeqStack(int n){ 25 top=0; 26 MaxStackSize=n; 27 data=new int[n]; 28 } 29 30 SeqStack::~SeqStack(){ 31 delete data; 32 } 33 34 void SeqStack::Push(const int item){ 35 if(this->top==this->MaxStackSize) 36 throw PushOnFull();//抛出异常 37 38 data[top]=item; 39 top++; 40 } 41 42 int SeqStack::Pop(){ 43 if(top==-1){//这里有个疑问,top==-1还是top==0合适 44 throw PopOnEmpty(); 45 } 46 top--; 47 return data[top]; 48 } 49 50 int main(){ 51 SeqStack myStack(10); 52 // try{ 53 // for(int i=0;i<11;i++){ 54 // myStack.Push(i); 55 // } 56 // }catch(PushOnFull){ 57 // cout<<"错误!堆栈已经满了"<<endl; 58 // } 59 60 try{ 61 for(int i=0;i<11;i++){ 62 cout<<myStack.Pop()<<endl; 63 } 64 }catch(PopOnEmpty){ 65 cout<<"错误!堆栈已经空了"<<endl; 66 } 67 return 0; 68 }
原文地址:https://www.cnblogs.com/Tobi/p/9250773.html
时间: 2024-11-29 01:44:21