operator<< overloading ostream

后端 未结 3 1774
离开以前
离开以前 2021-01-18 13:16

In order to use cout as such : std::cout << myObject, why do I have to pass an ostream object? I thought that was an implicit parameter.

ostream &o         


        
3条回答
  •  暖寄归人
    2021-01-18 13:40

    Only if it is a member function of the class that would otherwise be the first argument. Thus, it would be:

    class ostream {
        ...
        ostream &operator << (const myClass &o);
        ...
    };
    

    Since ostream was written long before your class, you see the problem of getting your class in there. Thus, we must implement the operator as a freestanding function:

    (return type) operator << ( (left hand side), (right hand side) );
    

    When operators are implemented as member-functions of classes, the left hand side is this, and the argument becomes the right hand side. (For binary operators - unary operators work similarly.)

提交回复
热议问题