vendredi 27 mars 2015

Relation between ostream insertion operator and its non-member overload


int i=0;
std::cout << i;


1, The non-member overload(two arguments, one being ostream& the other being type of operand, say int) is defined in std namespace. So if using namespace std; is not present, there's no way I see that the non-member overload can be called.


2, If instead, the member operator(member of ostream; one argument, being the type of operand, say int) function << of ostream is called, I'd expect something like: std::cout.operator<< i; --- isn't this rediculous?


So, what on earth is the relation between the two?


Question extended: if I want to overload the insertion operator so that std::cout << my_obj; works(assume my_obj is the instance of a user-defined type, MyType), should I do


a) ostream& operator<< (ostream& os, MyType obj); in the namespace of MyType


or


b) in MyType:



class MyType
{
...
ostream& operator<< (MyType);
};


does option b) ever work? Does it even make sense(I remember seeing it somewhere ...)? What's the relation between option a) & b)?


Thanks!


Aucun commentaire:

Enregistrer un commentaire