cc39b_demo_标准异常类c++例子_堆栈异常_继承异常

cc39b_demo_标准异常类c++例子_堆栈异常_继承异常

stack.h

//#pragma once
#ifndef STACK_H //头文件保护
#define STACK_H
#include <exception>//标准异常
#include <deque>//动态数组,stack的数据放在里面的

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 // !STACK_H

cc39b_demo.cpp

#include <iostream>
#include "stack.h"

using namespace std;

int main()
{
	try
	{
		Stack<int> st;
		st.push(1);
		st.push(2);
		st.push(3);
		cout <<"pop: "<< st.pop() << endl;//删除,pop出栈
		cout << "top: " << st.top() << endl;//top查看数据
		cout << "pop: " << st.pop() << endl;
		cout << "pop: " << st.pop() << endl;
		cout << "pop: " << st.pop() << endl;
	}
	catch (const exception &e)
	{
		cerr << "发生异常: " << e.what() << endl;
	}
	return 0;
}
发布了356 篇原创文章 · 获赞 186 · 访问量 89万+

猜你喜欢

转载自blog.csdn.net/txwtech/article/details/104070430
今日推荐