gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:21 27 4
gpt4 key购买 nike

我想做的是:

std::ofstream outFile (fname, std::ios::binary);
//...
outFile.flush();
outFile.close();

效果很好。但是当我尝试合并这两行时,因为 flush 返回了一个引用:

outFile.flush().close();

它给出错误提示:

error: ‘struct std::basic_ostream<char>’ has no member named ‘close’

然后我更仔细地查看了引用资料,发现它实际上返回 ostream instread of ofstream..

为什么会这样?是错误还是设计?

最佳答案

这是设计使然。

ostream 是一个包含将序列写入关联的流缓冲区的类,它是一个抽象类,负责写入和读取某物。某物可以是任何东西;文件、控制台、套接字等。

ofstream 实际上只是一个方便的类,它将 ostream 扩展为“自动”使用一种写入文件的流缓冲区,称为 filebuf ofstream 提供的函数只有openis_openclose;这些实际上只是底层 filebuf 流缓冲区对象的文件特定功能的简单接口(interface)。

如果你真的想要,你可以创建一个 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();

基本上,ofstream 实际上并没有做任何类型的写入,因此它没有实现像flushwrite 这样的功能。所有写入都是通过 ostream 类完成的,该类操作底层 streambuf 类,其工作是确保数据到达预期位置(即文件) .

关于c++ - 为什么 ofstream::flush() 返回 ostream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21951185/

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