错误关联器 C++实现

-----------------------------------------------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!
请按任意键继续. . .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值