---
title: "错误关联器 C++实现"
author: "pleasetojava"
date: "2011-11-20T18:18:00Z"
tags: []
slug: "c"
draft: false
lastmod: "2011-11-21T09:58:14Z"
id: 1270372
url: "https://pleasetojava.iteye.com/blog/1270372"
---

-----------------------------------------------ErrorCorrelator.h----------------------------------------------#include&lt;ostream&gt;  
#include&lt;string&gt;  
#include&lt;queue&gt;  
#include&lt;stdexcept&gt;

//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&lt;(const Error& lhs,const Error &rhs);

friend std::ostream& operator&lt;&lt;(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&lt;Error&gt; mErrors;

private:  
//prevent assignment and pass-by-refernence  
ErrorCorrelator(const ErrorCorrelator &src);

ErrorCorrelator & operator=(const ErrorCorrelator &rhs);

};

//比较符&lt;重载  
bool operator&lt;(const Error& lhs,const Error &rhs)  
{  
return lhs.mPriority&lt;rhs.mPriority;  
}

//输出符&lt;&lt;重载  
std::ostream& operator&lt;&lt;(std::ostream &str,const Error &err)  
{  
str &lt;&lt; err.mError &lt;&lt;"(priority "&lt;&lt;err.mPriority&lt;&lt;")"&lt;&lt;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&lt;iostream&gt;  
#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 &lt;&lt; e &lt;&lt; endl;  
}  
catch(out\_of\_range&)  
{  
cout&lt;&lt;"Finished processing errors!"&lt;&lt;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!  
请按任意键继续. . .