2011-12-03 5 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)は、たとえprivateであっても、RuntimeExceptionのサブクラスをキャッチします。これは、例外クラスを導出する全体のポイントです。

ところで、決してusing namespace std;を書いてはいけません、あなたはそれを誰がどのように含むのかわからないでしょう。また、標準ライブラリには既にあなたのgenereal目的の例外クラスがあります、そして、どんな驚きですか?彼らはまた、それはランタイム例外、それはstd::runtime_exceptionのように書かれた例外をclall。 <stdexcept>で見つけることができます。

関連する問題