我試圖使用鏈表來實現優先級隊列,但是我遇到了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的成員。任何建議將不勝感激。 謝謝
異常應該從'std :: exception'派生。另外,你爲什麼要把它作爲一個內部類,只是在外面定義它。 –
使EmptyPriorityQueueException爲public。目前它是一個私人嵌套類,從外部看不到。 – kol
**永遠不要在標題文件中使用'namespace std;'**。 –