When you are going to print an object, a friend operator<< is used. Can we use member function for operator<< ?
class A {
public:
void operator<
You have no choice -- it has to be a free function.
Note, however, that it need not necessarily be a friend
function. It only needs to be a friend if you actually need to grant it private access. For example, I use the following in programming competitions:
template
std::ostream& operator<<(std::ostream& os, const std::pair& p)
{
return os << '(' << p.first << ", " << p.second << ')';
}
No need for it to be friend, as first
and second
are accessible publicly.