首页 > 编程语言 > 详细

C++学习(31)

时间:2018-07-01 18:35:58      阅读:200      评论:0      收藏:0      [点我收藏+]
 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 }

 

 

技术分享图片

C++学习(31)

原文:https://www.cnblogs.com/Tobi/p/9250812.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!