制作自定义 cout 时出错

error while making custom cout

本文关键字:出错 cout 自定义      更新时间:2023-10-16

当我尝试运行不处理链接(out<<"one"<<"two")的代码版本时,我正在尝试创建一个自定义 cout 类,该类将文本输出到控制台输出和日志文件,它工作正常,但是当我尝试让它处理链接时,它给了我"这个运算符函数的参数太多"。我错过了什么?

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;
}};

你需要一个成员operator<<,它返回对对象实例的引用:

class CustomOut
{
  ...
  CustomOut& operator<<(string const& msg)
  {
    // Process message.
    f(msg);
    return *this;
  }
};

这将允许您以链接方式"流式传输"到CustomOut类中:

CustomOut out;
out << str_0 << str_i << ... << str_n;