C++学习(30)

 1 //设计一个数据元素为int类型的顺序堆栈类
 2 //要求:入栈操作异常时,异常处理模块中输出当前要入栈的数据元素值,并设计一个测试程序
 3 #include<iostream.h>
 4 
 5 class PushOnFull{
 6     private:
 7         int value;
 8     public:
 9         PushOnFull(int x){
10             value=x;
11         }
12         int Value(){
13             return value;
14         }
15 };
16 
17 class PopOnEmpty{
18 };
19 
20 class SeqStack{
21     private:
22         int *data;
23         int MaxStackSize;
24         int top;
25     public:
26         SeqStack(int n);
27         ~SeqStack();
28         
29         void Push(const int item);
30         int Pop();
31 };
32 
33 SeqStack::SeqStack(int n){
34     top=0;
35     MaxStackSize=n;
36     data=new int[n];
37 }
38 
39 SeqStack::~SeqStack(){
40     delete data;
41 }
42 
43 void SeqStack::Push(const int item){
44     if(this->top==this->MaxStackSize)
45         throw PushOnFull(item);//抛出异常
46     
47     data[top]=item;
48     top++;
49 }
50 
51 int SeqStack::Pop(){
52     if(top==-1){//这里有个疑问,top==-1还是top==0合适
53         throw PopOnEmpty();
54     }
55     top--;
56     return data[top];
57 }
58 
59 int main(){
60     SeqStack myStack(10);
61     try{
62         for(int i=0;i<11;i++){
63             myStack.Push(i);
64         }
65     }catch(PushOnFull obj){
66         cout<<"错误!堆栈已经满了"<<endl;
67         cout<<"当前要入栈的元素为"<<obj.Value()<<endl;
68     }
69     
70 //    try{
71 //        for(int i=0;i<11;i++){
72 //            cout<<myStack.Pop()<<endl;
73 //        }
74 //    }catch(PopOnEmpty){
75 //        cout<<"错误!堆栈已经空了"<<endl;
76 //    }
77     return 0;
78 }

猜你喜欢

转载自www.cnblogs.com/Tobi/p/9250785.html