how to cin a class object?

If you define a class, for example:


1
2
3
4
5
class line_t {
public:
    double x1,y1,x2,y2;
    int segment;
};


how to define constructor, so that when I type

1
2
line_t line1;
cin>>line1;


it will automatically require us to type in the values for x1,y1,x2,y2 and segment one by one?
Last edited on
The line1 object has already been constructed by line #2, so it' a bit late for the constructor to do it. For this scenario, overload the insertion operator for line_t objects like so:
1
2
3
4
5
istream& operator>>( istream& is, line_t& rLT)
{
    is >> rLT.x1 >> rLT.y1 >> rLT.x2 >> rLT.y2 >> rLT.segment;
    return is;
}

You could also supply a constructor overload that takes an istream reference:
1
2
3
4
line_t::line_t(istream& is)
{
     is >> x1 >> y1 >> x2 >> y2 >> segment;
}

Then your line #1 would become line_t line1(cin);
very useful inofrmation, thanks!

if I want use a file to input the line,

can I directly use

1
2
ifstream ifs;
ifs>>Line;


or do I need to define another function as?

1
2
3
4
5
ifstream& operator>>( ifstream& is, line_t& rLT)
{
    ifs >> rLT.x1 >> rLT.y1 >> rLT.x2 >> rLT.y2 >> rLT.segment;
    return is;
}

Last edited on
Topic archived. No new replies allowed.