2011-12-03 31 views
0

我試圖使用鏈表來實現優先級隊列,但是我遇到了try/catch問題。以下是優先級隊列的頭文件的相關部分:在模板類中定義異常的try-catch

#ifndef PRIORITYQUEUELINKED_H 
#define PRIORITYQUEUELINKED_H 

    #include "RuntimeException.h" 
    #include <list> 

    using namespace std; 

    template <typename E, typename C>  // uses data type and some total order relation 
    class PriorityQueueLinked { 

    // code for PriorityQueueLinked 

      class EmptyPriorityQueueException : public RuntimeException { 
       public: 
        EmptyPriorityQueueException() : 
            RuntimeException("Empty priority queue") {} 
      }; 

    // more code 

    #endif 

這裏是RuntimeException的頭文件:

#ifndef RUNTIMEEXCEPTION_H_ 
#define RUNTIMEEXCEPTION_H_ 

#include <string> 

class RuntimeException {// generic run-time exception 
private: 
    std::string errorMsg; 
public: 
    RuntimeException(const std::string& err) { errorMsg = err; } 
    std::string getMessage() const { return errorMsg; } 
}; 

inline std::ostream& operator<<(std::ostream& out, const RuntimeException& e) 
{ 
    out << e.getMessage(); 
    return out; 
} 

#endif 

這裏是我的主:

#include "PriorityQueueLinked.h" 
#include "Comparator.h" 
#include <iostream> 

using namespace std; 

int main() { 
    try { 
     PriorityQueueLinked<int,isLess> prique; // empty priority queue 
     prique.removeMin();     // throw EmptyPriorityQueueException 
    } 
    catch(...) { 
     cout << "error" << endl << endl; 
    } 
    getchar(); 
    return 0; 
} 

我的問題就在於不能夠爲捕獲配置替換「...」。我嘗試了幾件事情,其中​​之一是:「catch(PriorityQueueLinked < int,isLess> :: EmptyPriorityQueueException E)」,但在這種情況下,它表示EmptyPriorityQueueException不是PriorityQueueLinked的成員。任何建議將不勝感激。 謝謝

+2

異常應該從'std :: exception'派生。另外,你爲什麼要把它作爲一個內部類,只是在外面定義它。 –

+5

使EmptyPriorityQueueException爲public。目前它是一個私人嵌套類,從外部看不到。 – kol

+2

**永遠不要在標題文件中使用'namespace std;'**。 –

回答

1

Try-catch支持異常類的繼承。 catch (const RuntimeException & ex)將捕獲RuntimeException的任何子類,即使它是私有的。這是派生異常類的重點。

順便說一下,永遠不會寫using namespace std;是一個標題,你永遠不會知道誰包括它,以及如何。此外,標準庫已經有了你的基因目標異常類,真是一個驚喜!它們還會限制它的運行時異常,例外情況如下:std::runtime_exception。你可以在<stdexcept>找到它。