1

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

4

1 回答 1

7

例如,对于任意类,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";
}
于 2010-05-02T09:11:36.007 回答