How does the “return value” of operator >> of istream class work?

后端 未结 2 1363
隐瞒了意图╮
隐瞒了意图╮ 2021-01-20 20:57

I tried to understand the statement:

    int main() {
        fstream inf( \"ex.txt\", ios::in );
        char c;
        while( inf >> c ) {
                  


        
相关标签:
2条回答
  • 2021-01-20 21:05

    What does ( inf >> c ) return in the while loop above?

    void*. The loop test resolves to while (inf.operator void*() != NULL).

    How does a reference can be evaluated as true or false?

    But supporting conversion to bool or something convertible to bool.

    How does the internal implementation of istream actually work?

    It just returns a reference to itself (return *this) so it can support chaining.

    0 讨论(0)
  • 2021-01-20 21:13

    To return a self ref you just return *this. You don't actually declare an internal self reference. You can have reference members, but you must initialize them in the constructor initializer list: class Foo { Foo(int& some_int_ref) :my_ref_member(some_int_ref)

    istream has another overload to determine its boolean value.

    Example of a chainable member (like operator >>, but in this case just an ordinary function) and giving a class a boolean value (although the latter is a complex subject worthy of its own subject):

    #include <iostream>
    
    class X {
        bool B;
    public:
        X() :B(false) { }
        X& toggle() { B = !B; return *this; }
        operator void*() { return B ? this : 0; }
    };
    
    int main()
    {
        X x;
    
        x.toggle().toggle().toggle();
        if (x)
            std::cout << "true!" << std::endl;
    }
    

    EDIT: I didn't want to delve into operator bool vs operator void * in this answer, but this old stackoverflow question should give you good references: Why is "operator bool()" invoked when I cast to "long"?

    0 讨论(0)
提交回复
热议问题