Considering the following code:
namespace myNS {
class MyClass {
//.....
};
} //end of namespace myNS
using namespace myNS;
//overloading of '<<' operator
std::ostream &myNS::operator<<(std::ostream &os, MyClass &c){ /*....*/ }
In the last line, why is &myNS:: needed?
&is needed because, conventionally, streaming operators return a reference to the stream to allow them to be chained:with
something_elsebeing passed to the stream reference returned bystream << something.myNS::is needed if this operator is supposed to be scoped inside the namespace, in which case there must also be a previous declaration inside the namespace. If you want the operator to be in the current namespace (presumably the global namespace in this example), then it’s not needed.