【问题标题】:how to write any custom data type to file using ifstream?如何使用 ifstream 将任何自定义数据类型写入文件?
【发布时间】:2010-05-02 08:59:30
【问题描述】:

正如问题所说,我想在 c++ 中使用 ifstream 将类的自定义数据类型数据写入文件。需要帮助。

【问题讨论】:

  • 您想写入 ifstream 吗?诚然,我的 C++ 有点生疏,但这似乎是不可能的。
  • 是的,您需要ofstreamfstream

标签: c++ iostream fstream inserter


【解决方案1】:

对于任意类,例如Point,这是将其写入 ostream 的一种相当简洁的方法。

#include <iostream>

class Point
{
public:
    Point(int x, int y) : x_(x), y_(y) { }

    std::ostream& write(std::ostream& os) const
    {
        return os << "[" << x_ << ", " << y << "]";
    }

private:
    int x_, y_;

};

std::ostream& operator<<(std::ostream& os, const Point& point)
{
    return point.write(os);
}

int main() {
    Point point(20, 30);
    std::cout << "point = " << point << "\n";
}

【讨论】:

  • +1。我唯一想补充的是,如果不想在类本身中使用公共write 方法,可以将全局重载operator &lt;&lt;inserter)声明为@ 987654325@ 在类中,然后将write 设为私有,或者将其代码直接移动到插入器中。
  • 感谢您的建议,@stakx。我曾经将它编码为friend,没有write,但发现写point. 很乏味。我必须承认我从未考虑过私人write 选项。我想一旦你决定使用friend,重复前缀比私有write 更省力。
  • 事实上,我发现您的解决方案非常干净,公开的write 肯定不会受到伤害,尤其是。因为它与另一个开发人员沟通&lt;&lt; 插入器可能也可用于该类。我个人不是friend 的大朋友,但为了完整起见,我认为需要提及它。 ;)
  • 这里有一个错误。 write 应声明为 const。 std::ostream& write(std::ostream& os) 常量
猜你喜欢
  • 2015-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 2019-10-03
  • 2018-07-02
  • 1970-01-01
相关资源
最近更新 更多