--------------ErrorCorrelator.h----------------------------------------------#include<ostream>
#include<string>
#include<queue>
#include<stdexcept>
//error 類聲明
class Error
{
public:
Error(int priority,std::string errMsg):
mPriority(priority),mError(errMsg){}
int getPriority() const {return mPriority;}
std::string getErrorString() const {return mError;}
friend bool operator<(const Error& lhs,const Error &rhs);
friend std::ostream& operator<<(std::ostream &str,const Error &err);
protected:
int mPriority;
std::string mError;
};
//error類容器,返回最高優先級的錯誤
class ErrorCorrelator
{
public:
ErrorCorrelator(){};
////向優先隊列中添加元素
void addError(const Error& error);
//取得最優先元素
Error getError() throw (std::out_of_range);
protected:
std::priority_queue<Error> mErrors;
private:
//prevent assignment and pass-by-refernence
ErrorCorrelator(const ErrorCorrelator &src);
ErrorCorrelator & operator=(const ErrorCorrelator &rhs);
};
//比較符<重載
bool operator<(const Error& lhs,const Error &rhs)
{
return lhs.mPriority<rhs.mPriority;
}
//輸出符<<重載
std::ostream& operator<<(std::ostream &str,const Error &err)
{
str << err.mError <<"(priority "<<err.mPriority<<")"<<std::endl;
return (str);
}
//向優先隊列中添加元素
void ErrorCorrelator::addError(const Error &error)
{
mErrors.push(error);
}
//取得最優先元素
Error ErrorCorrelator::getError() throw(std::out_of_range)
{
//判斷優先隊列是否為空
if(mErrors.empty())
{
throw(std::out_of_range("No elements!"));
}
//獲取對頭元素
Error top = mErrors.top();
// 彈出隊頭元素
mErrors.pop();
return top;
}
---------------------------------------------------主函數-------------------------------------------------------
#include "stdafx.h"
#include<iostream>
#include "ErrorCorrelator.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ErrorCorrelator ec;
ec.addError(Error(3,"Unable to read file!"));
ec.addError(Error(1,"Incorrect entry from user!"));
ec.addError(Error(10,"Unable to allocate memory!"));
while(1)
{
try
{
Error e = ec.getError();
cout << e << endl;
}
catch(out_of_range&)
{
cout<<"Finished processing errors!"<<endl;
break;
}
}
system("pause");
return 0;
}
-----------------------------------------------------程序測試--------------------------------------------------Unable to allocate memory!(priority 10)
Unable to read file!(priority 3)
Incorrect entry from user!(priority 1)
Finished processing errors!
請按任意鍵繼續. . .
作者 heyongluoyao8