2016-04-21 44 views
2

我對這個計劃試圖一個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。

+0

你說'catch(...)'。 – molbdnilo

回答

3

您可以從一個共同的,未模板化基類派生的異常類,並捕獲引用到:

struct Stack_Full { }; 
struct Stack_Empty { }; 

template <class T> 
class stack{ 
    ... 
    class Full : public Stack_Full {}; 
    class Empty : public Stack_Empty {}; 
    ... 
}; 

... 
    catch (const Stack_Full&) { 

如果你不想只stack<T>::XYZ趕上一些T/XYZ,你可以throw直接的非模板化類型。您可能會也可能不想創建一個專用的非模板化類或名稱空間來保存這個類似的支持代碼。

+0

作品!謝謝。 –

+0

@GeorgeStop當然 - 不用擔心。乾杯。 –