C++学习(31)

 1 //在函数中抛出异常
 2 #include<iostream.h>
 3 
 4 class PushOnFull{
 5 };
 6 
 7 class PopOnEmpty{
 8 };
 9 
10 class SeqStack{
11     private:
12         int *data;
13         int MaxStackSize;
14         int top;
15     public:
16         SeqStack(int n);
17         ~SeqStack();
18         
19         void Push(const int item);
20         int Pop();
21 };
22 
23 SeqStack::SeqStack(int n){
24     top=0;
25     MaxStackSize=n;
26     data=new int[n];
27 }
28 
29 SeqStack::~SeqStack(){
30     delete data;
31 }
32 
33 void SeqStack::Push(const int item){
34     try{
35         if(this->top==this->MaxStackSize)
36             throw PushOnFull();//抛出异常
37         data[top]=item;
38         top++;
39     }catch(PushOnFull){
40         cout<<"堆栈已经满了"<<endl;
41     }
42     
43 }
44 
45 int SeqStack::Pop(){
46     try{
47         if(top==0){//这里有个疑问,top==-1还是top==0合适
48             throw PopOnEmpty();
49         }
50         top--;
51         return data[top];
52     }catch(PopOnEmpty){
53         cout<<"堆栈已经空了"<<endl;
54         return -1;
55     }
56     
57 }
58 
59 int main(){
60     SeqStack myStack(10);
61     for(int j=0;j<11;j++){
62         myStack.Push(j);
63     }
64 
65     for(int i=0;i<11;i++){
66         cout<<myStack.Pop()<<endl;
67     }
68     return 0;
69 }

 

 

posted on 2018-07-01 18:25  孙悟空son_ku_kong  阅读(112)  评论(0编辑  收藏  举报

导航