C++ Operator overloading example

前端 未结 3 1680
终归单人心
终归单人心 2021-01-25 19:08

Well, I\'m new to operator overloading, and I found this problem. Instead of documenting myself, I prefer to ask you :D

The point is, I know how to do simple operator ov

3条回答
  •  醉话见心
    2021-01-25 19:48

    The trick is to return a reference to youself from operator << - this way, the operator can be 'stacked'.

    class me {
    
        me& operator<<(int t) {...; return *this;}
    };
    
    me m;
    m << 4 << 5 << 6;
    

    Just overload the shift operator for all types you wish to support (or make it a template if you can afford the danger)!

提交回复
热议问题