我已经重写了 std::ostream::flush()
函数。下面我从示例中删除了所有其他代码:
#include <iostream>
#include <ostream>
class CMyStream : public std::streambuf, public std::ostream
{
public:
explicit CMyStream() throw() : std::ostream(this)
{
// Intentionally empty block
}
std::ostream &flush()
{
std::cout << "Overridden flush called\n";
return (*this);
}
int sync()
{
std::cout << "Overridden sync called\n";
return 0; // Success
}
};
我尝试这样使用它:
CMyStream myStream;
myStream << "Test" << std::flush;
,但覆盖的 CMyStream::flush()
或 CMyStream::sync()
函数不会由 std::flush
调用> 机械手。如果我调试,我会看到默认的 std::ostream::flush()
被调用,而不是我的重写函数。
有办法解决这个问题,还是我必须直接调用 myStream.flush()
而不是使用操纵器?
最佳答案
问题是 std::ostream::flush
方法不是虚拟的,所以你不能正确地重写它,你也不应该这样做。相反,您应该做的是创建自己的缓冲区类,继承自 std::basic_streambuf
或 std::basic_filebuf
或 std::basic_stringbuf
并且重写其中 protected intsync()
方法。然后,您的流类应该在其构造函数中创建正确的缓冲区类型。
关于c++ - std::flush 未调用重写的 std::ostreamlush() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25019067/