简体   繁体   中英

how to write any custom data type to file using ifstream?

as question says, i want to write custom data type data of a class maybe to a file using ifstream in c++. Need help.

For an arbitrary class, say, Point , here's a fairly clean way to write it out to an 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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM