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

后端 未结 2 1367
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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 
    
    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"?

提交回复
热议问题