为什么ofstream :: flush()返回ostream?

tex*_*uce 6 c++ file ofstream

我试图这样做:

std::ofstream outFile (fname, std::ios::binary);
//...
outFile.flush();
outFile.close();
Run Code Online (Sandbox Code Playgroud)

哪个工作正常.但是当我尝试将两行合并时,flush会返回一个引用:

outFile.flush().close();
Run Code Online (Sandbox Code Playgroud)

它给出了错误说:

error: ‘struct std::basic_ostream<char>’ has no member named ‘close’
Run Code Online (Sandbox Code Playgroud)

然后我仔细查看了参考文献,发现它实际上返回了ostream实例ofstream...

这是为什么?这是一个bug还是设计的?

Col*_*nee 6

这是设计的.

ostream是包含写一个序列到相关联的一类数据流缓存器,它是一个抽象类,它是在电荷写入和读取到的东西.那可能是什么东西; 文件,控制台,套接字等

ofstream实际上只是一个便利类,它扩展ostream为"自动"使用一种写入文件的流缓冲区,称为filebuf.由所提供的唯一功能ofstreamopen,is_open,和close; 这些只是基础filebuf流缓冲区对象的特定于文件的功能的简单接口.

如果你真的想要,你可以创建一个ostream完全相同的东西ofstream.它只需要更多的代码,而不是很漂亮或明确.

std::filebuf f;
f.open(fname, std::ios::binary);

std::ostream os(&f);
os.write("Hello world!", 12);
os.flush();

// Error! close() isn't part of the streambuf interface, it's specific to
// files.
os.close();
Run Code Online (Sandbox Code Playgroud)

基本上,ofstream实际上并没有做任何类型的写作,所以它没有实现像flush和的功能write.所有的写作都是通过ostream类来完成的,它操作一个底层streambuf类,它的工作是确保数据到达它的预期位置(即文件).