异常3

来源:互联网 发布:网站空间域名续费 编辑:程序博客网 时间:2024/06/16 03:54
#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   // 自己创建一个异常,{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



#include <iostream>#include "Stack.h"using namespace std;int main (){try{   Stack<int> st;   st.push(1);   st.push(2);   st.push(3);   cout << st.pop() << endl;  // 输出的3。   cout << st.pop() << endl;  // 输出的2   cout << st.top() << endl;  // 输出的1,   cout << st.pop() << endl;  // 输出的1,   cout << st.top() << endl;  //  出错,}catch (const exception &e){cerr << "发生异常:" << e.what() << endl;}   cout << "Hello Stack" << endl;return 0;}


0 0
原创粉丝点击