简体   繁体   中英

Operator overloading for << and >> does not work stream object in argument is const &

I have a confusion. I am making a set class and when I overload the << or >> operators with this prototype:

ostream& operator<<(const ostream & out, Set & argSet)
{
    //whatever my code does
    return out;
}

It does not work. But if I remove the "const" keyword in first argument, it works. I am confused why it is not working. Any help will be appreciated.

But if I remove the "const" keyword in first argument, it works. I am confused why it is not working.

In both cases (overloading operator<<() and operator>>() ) for the ostream& and the istream& references the stream state is usually changed by the operations made inside, thus these can't be const references.

One obvious reason you can't do so, is the required return type that can't be implicitly changed from const reference to non const reference.

The stream cannot be const because its internal state has to be able to change upon insertion/extraction or other operations.

For instance, if it were to reach EOF, how would it set the relevant bit ( eofbit )?

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