I researched and found out that when you want to overload the output stream operator for cout, then the correct way to do it is as follows:
std::ostream& operator<<(std::ostream& os, const T& obj)
This function must be defined outside the class, because what happens here is that the <operator is actually a friend function defined in ostream, and you use it. But, the question is, how exactly is this function defined in ostream? Since this function takes 2 parameters, and the second parameter is user-defined, there is no way that they can guess what is happening there.
Overloading for a specific class should look like this:
std::ostream& operator<<(std::ostream& os, const MyClass& obj)
How does the compiler / library accept the general definition for the second parameter, especially since in C ++ there is no such thing as a general class (such as Object in Java)?
source
share