我正在尝试创建一个自定义cout类,当我尝试运行不处理链接的代码版本时输出文本到控制台输出和日志文件(out<<“one”<<“two “)它工作正常,但是当我试图使它处理链接时它给了我”这个操作符函数的参数太多“。我错过了什么?
class CustomOut
{
ofstream of;
public:
CustomOut()
{
of.open("d:\\NIDSLog.txt", ios::ate | ios::app);
}
~CustomOut()
{
of.close();
}
CustomOut operator<<(CustomOut& me, string msg)
{
of<<msg;
cout<<msg;
return this;
}};
答案 0 :(得分:5)
您需要一个成员operator<<
,它返回对对象实例的引用:
class CustomOut
{
...
CustomOut& operator<<(string const& msg)
{
// Process message.
f(msg);
return *this;
}
};
这将允许您以链接方式“流”到您的CustomOut
班级:
CustomOut out;
out << str_0 << str_i << ... << str_n;