首页 > 编程语言 > 详细

C++中自定义异常类

时间:2015-05-24 08:53:12      阅读:122      评论:0      收藏:0      [点我收藏+]

头文件Stack.h

#ifndef STACK_H
#define STACK_H
#include <exception>
#include <deque>
using namespace std;
class ReadEmptyStackError : public exception
{
public:
virtual const char * what() const throw()
{
return "error: stack is empty!!";
}
private:


};
template<class T>
class Stack
{
public:

void push(const T& elem)
{
c.push_back(elem);
}
bool empty() const
{
return c.empty();
}
T pop()
{
if (empty())
{
throw ReadEmptyStackError();
}
T elem(c.back());
c.pop_back();
return elem;
}
T& top()
{
if (empty())
{
throw ReadEmptyStackError();
}
return c.back();
}
private:
std::deque<T> c;
};
#endif



源文件main.cpp:

#include <iostream>

#include "Stack.h"
using namespace std;


void main(){
try
{
Stack<int> s;
s.push(3);
s.push(4);
cout<<s.pop()<<endl;
cout<<s.pop()<<endl;
cout<<s.pop()<<endl;
}
catch(ReadEmptyStackError e)
{
cout<<e.what()<<endl;
}
}

C++中自定义异常类

原文:http://blog.csdn.net/jean_bai/article/details/45939009

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!