Arguments must be const
:
friend bool operator==(const MyClass& lhs, const MyClass& rhs);
This is preferable since it works when the first argument can be implicitly constructed. For example, if std::string
has only a member function operator==
, then "abc" == my_std_string
will not call it! But the non-member function can be called by implicitly building the string from "abc" (even better in this particular case, for convenience in performance, a separate bool operator==(const char*, const std::string&)
can be provided, but the point is all still worth it - non-member functions can help the operator work with the user type on both sides).
Separately, implicit constructors are a little dangerous - and you want to seriously think about the convenience and danger of using them.
Endpoint: you need to make no member operator==
a friend
if there is no other way to access the data you need to compare. Otherwise, you can declare / define it outside the class, optional if you want to implement the implementation in the header, which can be included from several translation units, which ultimately are associated with the same executable file. There is not much harm, and making it a friend is the only way to put a definition inside a class template where you do not need to repeat the material and parameters of the template ....
source share