c++ - fstream 和 ofstream 运算符 << 区别

标签 c++

我想重载 operator<< 以将对象序列化到文件(追加)。我应该使用哪个流? ofstream 还是 fstream?有什么区别?

std::ofstream& operator<<(std::ofstream& ofs, const MyData&);
std::fstream& operator<<(std::fstream& fs, const MyData&)

谢谢 jack

最佳答案

您应该重载 ostream 的运算符,然后您可以自然地将它用于派生自该运算符的任何类的实例 - ofstream、fstream(继承自 iostream,它继承自 istream 和 ostream)、ostringstream 和 stringstream(继承iostream也是)

std::ostream& operator<<(std::ostream& os, const MyData&);

关于c++ - fstream 和 ofstream 运算符 << 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3171588/

相关文章:

c++ - opengl如何知道有多少个顶点?

c++ - __FLT_MAX__ 和 __DBL_MAX__ 为 0?

c++ - 从构造函数中抛出异常

c++ - 调用构造函数而不将其分配给任何变量c++

c++ - VS2010 在不同平台上生成的可执行文件应该不同吗?

c++ - 使用 C++,使用 QWebView 显示 HTML 文本,而不是网络上某处的网页

c++ - 为什么允许 pthread_cond_wait() 有时获得虚假唤醒会提高性能?

C++: "(static const double variable) cannot appear in constant-expression"

c# - 传递结构似乎会损坏数据

C++ 继承 - 无法在 cpp 文件中定义方法