2011-12-03 2 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에 대한 "..."대체를 구성 할 수 있습니다. 나는 여러 가지 중 하나를 시도했습니다 : "catch (PriorityQueueLinked < int, isLess> :: EmptyPriorityQueueException E)"이 경우 EmptyPriorityQueueException은 PriorityQueueLinked의 멤버가 아닙니다. 모든 조언을 크게 주시면 감사하겠습니다. 감사

+2

예외는'std :: exception'에서 파생되어야합니다. 또한, 왜 당신은 그것을 내부 클래스로 만들고 있습니까, 그냥 외부에 정의하십시오. –

+5

EmptyPriorityQueueException을 공개로 설정하십시오. 현재이 클래스는 외부에서 볼 수없는 개인 중첩 클래스입니다. – kol

+2

** 헤더 파일에'using namespace std;'**를 절대로 사용하지 마십시오. –

답변

1

시도 - 캐치 예외 클래스와 상속을 지원합니다. catch (const RuntimeException & ex)은 Private 클래스 인 경우 라하더라도 RuntimeException의 하위 클래스를 포착합니다. 이것은 예외 클래스를 파생시키는 요점입니다. 그런데

, using namespace std;가 헤더 인 쓰기 결코, 당신은 그것을 포함, 어떻게 누구인지 알 수 없다. 또한 표준 라이브러리에는 이미 여러분의 genereal 목적 예외 클래스가 있으며, 놀랍습니다! 그들은 또한 다음과 같이 쓰여진 런타임 예외 (exception exception)라고 호평합니다 : std::runtime_exception. <stdexcept>에서 찾을 수 있습니다.

관련 문제