views:

90

answers:

1

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

+4  A: 

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)
    {
        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";
}
Marcelo Cantos
+1. The only thing I'd like to add is that if one doesn't want a public `write` method in the class itself, one could declare the global overloaded `operator <<` (the _inserter_) as `friend` inside the class and then either make `write` private, or move its code directly into the inserter.
stakx
Thank you for suggestion, @stakx. I used to code it up as a `friend` without a `write`, but found that it was tedious to write `point.`. I must admit that I never considered the private `write` option. I guess once you decide to use a `friend`, the repeated prefix is less effort than a private `write`.
Marcelo Cantos
@Marcelo Cantos: In fact, I find your solution very clean and a public `write` certainly doesn't hurt, esp. as it communicates to another developer that a `<<` inserter is probably available for that class, too. I am personally no big friend of `friend` but thought it needed to be mentioned for completeness' sake. ;)
stakx