c++ - 如何将字符串作为二进制文件写入文件?

标签 c++

这是一道 C++ 题。我有一个包含字符串的类:

class MyClass{
public:
std::string s;
};

我有一个 MyClass 对象数组:

MyClass * array = MyClass[3];

现在我想将数组作为二进制文件写入文件。我不能使用:

Ofstream.write((char *)array, 3 * sizeof(MyClass))

因为 MyClass 的大小不同。

如何使用Ofstream.write来达到目的呢?非常感谢。

最佳答案

过载 operator<<为你的类(class)。你可以这样做:

ostream& operator<< (ostream& os, const MyClass& mc)
{
  return os << mc.s /* << ... other members*/ << endl;
}

关于c++ - 如何将字符串作为二进制文件写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1378197/

相关文章:

c++ - for-each 循环生成错误,但是 for(it=begin()... 在遍历包含 unique_ptr 的 std::map 时不会生成错误

c++ - Qt; QWidget 移除和删除。 setParent(NULL) 有必要吗?

c# - 用投影搭建互动楼层?

c++ - 优化代码 - CPU 与内存

c++ - 内联函数时出现链接器错误

javascript - switch case 语句中的分号

c++ - 如何在 C++ 中正确使用命名空间?

C++ "undefined reference to class::function"

c++ - 你能混合使用同一个编译器的不同版本编译的c++吗

c++ - 在 C++ 中嵌入 matplotlib