本题重点在于抛出异常的类型,异常既可以抛出内置类型的数据,也可以抛出自定义的类型,设计一个关于栈的简单类,并且添加异常处理,判断栈空和栈溢出,在主程序中对其进行测试。
函数接口定义:
在这里描述相关类和函数接口:
#include<iostream>
const int SIZE=10;
using namespace std;
class Full
{
private:
int a;
public:
Full(int i);
int getValue();
};
class Empty
{
public:
void show();
};
class Stack
{
private:
int stack[SIZE];
int tos;
public:
Stack();
void push(int a);
int pop();
int top()const;
};
裁判测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
int main()
{
Stack s;
int b[20],i=0;
try
{
cin>>b[i];
while(b[i])
{
s.push(b[i]);
++i;
cin>>b[i];
}
for(i=0;i<SIZE;i++)
cout<<s.pop();
}
catch(Full e)
{
cout<<"Exception: Stack Full..."<<endl;
cout<<"The value not push in stack: "<<e.getValue()<<endl;
}
catch(Empty e)
{
e.show();
}
return 0;
}
/* 请在这里填写答案 */
输入样例1:
在这里给出一组输入,遇到0结束输入:
1 2 3 0
输出样例1:
在这里给出相应的输出,首先栈内元素出栈;若继续出栈,抛出异常”栈空“:
321stack is empty!
输入样例2:
在这里给出一组输入,输入11个元素:
1 2 3 4 5 6 7 8 9 10 11
输出样例2:
在这里给出相应的输出,因元素超出栈的容量,抛出异常,并显示栈满“:
Exception: Stack Full...
The value not push in stack: 11
答案代码加注释如下:
Full::Full(int i)
{
a=i; // 栈满后加入的元素,赋值给a
}
int Full::getValue()
{
return a; //抛出栈满后的元素
}
void Empty::show()
{
cout<<"stack is empty!"<<endl;
}
Stack::Stack()//构造函数
{
tos=-1; //类似栈的头指针,用来判断栈满栈空
}
void Stack::push(int a)//入栈
{
if(tos>=SIZE-1) //先判断栈满栈空,此时说明栈满
{
throw Full(a); //抛出栈满后的元素
}
else
{
stack[++tos]=a; //否则就入栈
}
}
int Stack::pop()//出栈
{
if(tos==-1) //此时栈为空
{
throw Empty(); //这个是根据catch捕获的数据类型来决定要抛出什么类型的数据
}
else
{
return stack[tos--]; //出栈相应的tos--
}
}
没有什么难度,重点在大家掌握栈的机制,本质还是判断会出现异常的情况然后相应处理。
该博客介绍了一个关于栈的简单类设计,包括异常处理机制,用于判断栈空和栈溢出。在主程序中,通过测试用例展示了如何在栈满或栈空时抛出自定义异常`Full`和`Empty`。当尝试在满栈上插入元素时,抛出`Full`异常并显示未入栈的值;当尝试从空栈中弹出元素时,抛出`Empty`异常并提示栈为空。
552

被折叠的 条评论
为什么被折叠?



