您的位置:首页 > 其它

自己创建一个异常

2016-03-28 19:50 309 查看
#ifndef STACK_H
#define STACK_H

#include <deque>
#include <exception>

template<class T>
class Stack
{
protected:
std::deque<T> c;
public:
class ReadEmptyStack : public std::exception   //exception 是标准异常,
{
public:
virtual const char * what() const throw()
{
return "read empty stack 堆栈是空的";
}
};
bool empty() const
{
return c.empty();
}
void push(const T& elem)
{
c.push_back(elem);
}
T pop()  // 抛出数据,
{
if(c.empty())
{
throw ReadEmptyStack();
}
T elem(c.back());
c.pop_back();
return elem;
}
T& top()  // 读数据,
{
if(c.empty())
{
throw ReadEmptyStack();
}
return c.back();
}
};

#endif
<pre name="code" class="cpp">#include <iostream>#include "Stack.h"using namespace std;int main(){try{Stack<int> s;s.push(4);s.push(7);cout << "pop : " << s.pop() << endl;cout << "top: " << s.top() << endl;cout << "pop: " << s.pop() << endl;cout << "top: " << s.top() << endl;}catch(const exception& e){cerr << "发生异常:" << e.what() << endl;}cout << "xiao cui " << endl;return 0;}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: