In some books and often around the internet I see recommendations like “operator== should be declared as friend”.
How should I understand when an operator must be declared as friend and when it should be declared as member? What are the operators that will most often need to be declared as friends besides == and <<?
This really depends on whether a class is going to be on the left- or right-hand side of the call to
operator==(or other operator). If a class is going to be on the right-hand side of the expression—and does not provide an implicit conversion to a type that can be compared with the left-hand side—you need to implementoperator==as a separate function or as afriendof the class. If the operator needs to access private class data, it must be declared as afriend.For example,
allows you to compare a message to a string
but not the other way around
You need to declare a friend
operator==inside the classor declare an implicit conversion operator to the appropriate type
or declare a separate function, which doesn’t need to be a friend if it doesn’t access private class data