Operator == - member function or friend function ,?

Is it useful or required to do operator== , operator< , operator> , operator<< , operator>> != , >= , ... as a friend, not a class method?

I did not find a good text that explains why you need to go only in a friendly way ...

I have a good use case if C1 x; C2 y; C3 z; C1 x; C2 y; C3 z; , and I have C3& operator+(C1& , C2&) as a friend in C1 and C2, i.e. when the classes are different, but the question is why for the same class.

+4
source share
3 answers

The argument for autonomous functions is that these operators must be symmetric according to the types of operands. Implementing relational operators as stand-alone functions rather than methods can have advantages when your class has constructors that allow you to implicitly convert the left operand to your class type. Otherwise, you will have to write explicit constructor calls or overload the operator for other types of left operand (combinatorial explosion).

A friendly declaration is only necessary if you must have access to members of your class. Since relational operators do not need to modify their operands at all, in most cases there are other ways to read members.

Do not use excessive operator overload. Especially when you have many types of classes, such as C1, C2, C3 in your question, it soon becomes unclear, especially for other developers, what your operators say. Consider using a function with a name that clearly describes your intent.

+2
source

If your class has relational semantics, then make relational operators part of the class. On the other hand, if you need something like < to arrange your class for a container, you might prefer to write a separate free function for the explicit purpose of defining that container, rather than implying that it is related to the semantics of the class (or you you can specialize std::less for your class).

For binary shift operators << and >> you may not have a choice, because a member function is selected only when the class object is the first argument to the operation. Other than that, I would give the same advice, and I would make a member statement only if this operation is somehow an integral part of the semantics of the class, and not with the help of some other, unrelated goal.

+1
source

Friend functions are preferred because they allow you to use this function in cases such as:

 bool b = (12345 == myObj); 

This will result in a compiler error if operator== is defined as a member function.

+1
source

Source: https://habr.com/ru/post/1399634/


All Articles