Operator << ostream overload

To use cout as such: std :: cout <myObject, why do I need to pass an ostream object? I thought this was an implicit parameter.

ostream &operator<<(ostream &out, const myClass &o) {

    out << o.fname << " " << o.lname;
    return out;
}

thank

+5
source share
3 answers

You are not adding another member function to ostream, as that would require overriding the class. You cannot add it in myClass, as it will be at first ostream. The only thing you can do is add overloading to an independent function, what you are doing in this example.

+5
source

- , . , :

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

ostream , . , :

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

- , this, . ( - .)

+2

Because you are overloading a free function, not a member function.

-1
source

All Articles