#include <iostream>
#include <vector>
#include <string>
#include <exception>
using namespace std;
template <typename T>
class Stack{
public:
void push(const T elem)
{
Elems.push_back(elem);//在模板类的内部定义成员模板可以省略模板参数部分
}
void pop();
T top() const;
private:
vector<T> Elems;
};
//template <typename T>
//void Stack<T>::push(const T elem)
//{
// Elems.push_back(elem);
//}
template <typename T>
void Stack<T>::pop()
{
if(Elems.empty())
{
throw out_of_range("Stack<>::pop():empty stack");//terminates the execution
}
Elems.pop_back();
}
template <typename T>
T Stack<T>::top() const
{
if(Elems.empty())
{
throw out_of_range("Stack<>::top():empty stack");
}
return Elems.back();
}
int main()
{
try
{
Stack<int> intStack;
intStack.push(5);
intStack.push(8);
cout << intStack.top() << endl;
intStack.pop();
cout << intStack.top() << endl;
intStack.pop();
cout << intStack.top() << endl;
intStack.pop();
}
catch (const exception& ex )
{
cerr << ex.what() << endl;
//return -1;
}
try
{
Stack<string> strStack;
cout << strStack.top() << endl;
strStack.pop();
}
catch (const exception &ex)//捕捉类型与抛出类型一致,抛出类型可以使类、string、exception等c++类型
{
cerr << ex.what() << endl;
}
}
// if a function throws a exception without a try-catch block , it will eventually terminate the whole program