制作自定义cout时出错

yoh*_*nes 3 c++

我正在尝试创建一个自定义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;
}};
Run Code Online (Sandbox Code Playgroud)

mav*_*vam 5

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

class CustomOut
{
  ...

  CustomOut& operator<<(string const& msg)
  {
    // Process message.
    f(msg);

    return *this;
  }
};
Run Code Online (Sandbox Code Playgroud)

这将允许您以CustomOut链接方式"流"到您的班级:

CustomOut out;
out << str_0 << str_i << ... << str_n;
Run Code Online (Sandbox Code Playgroud)