自己创建一个异常
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;}
相关文章推荐
- C#事件
- 第四周项目4-程序分析(3)
- 常用正则表达式
- poj 1664[dfs]
- Hacker 学习发展流程图
- Java 设计模式-适配器模式
- 关于iOS系统架构的理解
- bzoj3205 机器人 斯坦纳树
- Kotlin
- Android横竖屏切换总结
- notes on virtio-blk driver
- web前端兼容问题
- HDU4276 The Ghost Blows Light(树形DP+背包)
- Android AndroidManifest 清单文件以及权限具体解释
- Log4j配置具体解释
- NHibernate3.2学习笔记-几种查询方式
- 三角形3
- HDU 5651xiaoxin juju needs help 带模除法逆元+有重复元素的全排列值
- 2016春季练习——位运算
- 推荐算法分类:协同过滤、聚类、分类