Use operator overloading to provide a
friend right-shift operator, operator>>. This is
similar to the output operator, except the
parameter doesn't have a const: "Fred&"
rather than "Fred const&".
#include <iostream>
class Fred {
public:
friend std::istream& operator>> (std::istream& i, Fred& fred);
...
private:
int i_; // Just for illustration
};
std::istream& operator>> (std::istream& i, Fred& fred)
{
return i >> fred.i_;
}
int main()
{
Fred f;
std::cout << "Enter a Fred object: ";
std::cin >> f;
...
}
Note that
operator>> returns the stream. This is so the input operations can
be
cascaded and/or used in a while loop or if
statement.