gpt4 book ai didi

c++ - 制作自定义 cout 时出错

转载 作者:太空狗 更新时间:2023-10-29 20:44:55 25 4
gpt4 key购买 nike

我正在尝试制作一个自定义 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;
}};

最佳答案

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

class CustomOut
{
...

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

return *this;
}
};

这将允许您“流式传输”到您的 CustomOut 中以链式方式上课:

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

关于c++ - 制作自定义 cout 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11974206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com