我對這個計劃試圖一個try-catch你在主看不過來,我只能抓誤差分別爲這裏的例子,我只能抓字符:如何捕獲所有類型的堆棧錯誤?
catch (stack<char>::Empty)
不過,我要趕所有類型的錯誤,雙精度,字符串等...我該怎麼做?
#include <iostream>
using namespace std;
template <class T>
class stack{
T *s;
int size;
int top;
public:
//neww
class Full{};
class Empty{};
//neww
stack(int sz)
{
size=sz;
s = new T[sz];
top=-1;
}
void push(T e);
T pop()
{
if (top<0)
throw Empty();
return s[top--];
}
};
template <class T>
void stack<T>::push(T e)
{
if (top>=size)
throw Full();
s[++top]=e;
}
int main()
{
stack<char> s(5);
try {
s.pop();
s.push('a');
s.push('b');
cout<<s.pop()<<endl;
stack<double> s1(10);
s1.push(3.2);
s1.push(0.5);
cout<<s1.pop()<<endl;
}
catch (stack<char>::Full) {
cout <<"Stack is full!"<<endl;
return 1;
}
catch (stack<char>::Empty) {
cout <<"Stack is empty!"<<endl;
return 1;
}
return 0;
}
我不能做catch(...),因爲我需要處理兩種類型的異常,full和empty。
你說'catch(...)'。 – molbdnilo