c++operator-overloadingistream

Operator>> overloading: "cannot bind 'std::istream {aka std::basic_istream<char>}' lvalue to 'std::basic_istream<char>&&'"


Here's my fraction class:

class fraction { // type definition
    int num;
    int denom;
    ostringstream sstr;
public:
    fraction(int c=0, int d=1) :
    num(c), denom(d)
    { sstr = ostringstream(); }

    fraction(const fraction &f) : num(f.num), denom(f.denom) { /*void*/ }

    friend ostream& operator<<(ostream &os, const fraction &f){
        os << "(" << f.num << "/" << f.denom << ")"; 
        return os;
    }

    friend istream& operator>>(istream &is, const fraction &f){
        is >> "(" >> f.num >> "/" >> f.denom >> ")"; // Exception thrown on this line on "is >>"
        return is;
    }

Overloading the operator<< works, but operator>> throws an error:

cannot bind 'std::istream {aka std::basic_istream<char>}' lvalue to 'std::basic_istream<char>&&'

I have looked at other questions here on SO, but still have no idea why this could be. I think it might have something to do with pointers, but I am clueless. Please note that I'm really new to C++, so there might be some obvious flaws in my code, feel free to point them out in a comment.


Solution

  • Remove the const:

    friend istream& operator>>(istream &is, fraction &f){
    

    Clearly, since operator>> is modifying f, it should not be const.

    On the other hand, the const in operator<< is correct, because that function does not modify f.

    Also, is >> "(" is incorrect. Not clear what you intend by that, but you cannot read into a string literal. You can only read into variables (more or less).

    BTW, that's not an exception being thrown on that line, it's an error message being generated from that line. An exception is something completely different.