📄 用异常的栈.txt
字号:
/* 本程序献给我的志爱老婆冯琼。
为了说明异常的抛出和接受的情况。见c++primer 3/e 第11章 异常处理p450
本程序围绕由类iStack的两个成员函数pop()和push()抛出的异常popOnEmpty和pushOnFull进行。
作者:陈朝钢。 完成日期:2006.5.24
*/
#include <vector>
#include <iostream>
using namespace std;
class popOnEmpty { //异常类1
};
class pushOnFull { //异常类2
public:
pushOnFull( int value ){ _value = value;}
int GetValue() { return _value;}
private:
int _value; //_value 保存不能插入栈的数据
}; //注意class定义好了以后,分号不能漏掉
class iStack {
public:
iStack( int capacity )
: _stack( capacity ), _top( 0 ) {}
void pop(int & top_value ) throw( popOnEmpty );
void push( int value ) throw( pushOnFull );
bool full();
bool empty();
void display();
int size();
private:
int _top; //下一个可用槽的下标值,也是当前栈中的数据元素个数
vector< int > _stack;
};
inline int iStack::size() //栈里面有多少数
{
return _top;
}
inline bool iStack::full() //若栈满了则返回真
{
if ( _top <= (_stack.size() - 1) )
return false;
else
return true;
}
inline bool iStack::empty() //若栈空返回真
{
return _top ? false : true;
}
void iStack::pop(int & top_value) throw( popOnEmpty ) //从栈中弹出栈顶,并用top_value返回,若空则输出出错。
{
if ( empty() )
{
cout << "由iStack::pop()函数抛出异常popOnEmpty!" << endl;
throw popOnEmpty();
}
top_value = _stack[ --_top ];
cout << "iStack::pop() " << top_value << endl;
}
void iStack::push( int value ) throw( pushOnFull ) //向栈中插入一个数,若满了则显示出错
{
if ( full() )
{
cout << "由iStack::push()函数抛出异常pushOnFull!" << endl;
throw pushOnFull( value );
}
_stack[ _top++ ] = value;
}
void iStack::display() //显示栈中的每一个数字
{
if ( empty() )
{
cout << " The stack is empty !" << endl;
return;
}
cout << "the stack is " << _top << "(" << '\t';
int index;
for( index = 0; index < _top; ++index )
{
cout << _stack[ index ] << " ";
}
cout<<")";
cout << endl;
}
const int stackSize = 32;
int main()
{
const int stackSize = 32; //我在编写这一句的时候把 = 号给忘了,系统报错很奇怪: error C2143: 语法错误 : 缺少“;”(在“常数”的前面)
//和 error C2734: “stackSize” : 如果不是外部的,则必须初始化常数对象
iStack stack( stackSize );
try
{
int index1;
for( index1 = 0; index1 < 132; ++index1) //将数字改一下,改成大于stackSize或是小于它
{
stack.push( index1); //当index1 = stackSize 的时候就抛出异常
}
cout << " 如果没有异常被抛出则打印出栈中的全部数据! " << endl;
stack.display(); //当有异常抛出的时候这一句被忽律了。
}
catch ( popOnEmpty )
{
cerr << " The stack is empty! " << endl <<endl;
//试图在这里操作try里面的变量index1;会导致编译出错。见c++primer P454页中间说明的:一个try块
//引入了一个局部域,在 try块内声明的变量不能在try块外面被引用,包括在catch子句中。
}
catch( pushOnFull & val)
{
cerr << "PushOnFull异常被接收!" << endl;
cerr << "The stack is full, push " << val.GetValue() << " failed" <<endl<<endl;
}
cout << "不管异常有没有抛出,我都会笑一下:哈哈哈哈哈哈哈哈哈哈!"<<endl; //catch 异常处理之后执行这一句。
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -