C ++ operator == overload

Possible duplicate:
Operator Overload

What is the difference between the following ways to overload the == operator?

// stroustrup way friend bool operator== (MyClass &lhs, MyClass &rhs); 

and

 // as taught in other places, including caltech bool MyClass::operator== (MyClass &rhs); 

Which way is better?

+6
source share
3 answers
 // stroustrup way friend bool operator== (MyClass &lhs, MyClass &rhs); 

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 ....

+4
source

First function of an external friend (free function)

 friend bool operator== (MyClass &lhs, MyClass &rhs); 

Second member function

 bool MyClass::operator== (MyClass &rhs); 

You should always use the second option, then you can

You should use the first option in the case of: 1) The first argument is an external (library) class

 friend ostream& operator<< (ostream &out, MyClass &m) 

2) The operator logic is not related to your class and must be implemented separately

 friend bool operator(const MyClass& my, const std::string& string_form) 

(because your class cannot know everything about the classes that may be required in the comparison operator)

+2
source

It:

 friend bool operator== (MyClass &lhs, MyClass &rhs); 

is a function that compares two objects.

It:

 bool MyClass::operator== (MyClass &rhs); 

is a member function.

You should use the one offered by the coding standard, or use the one you prefer. No, better. Some people (including me) prefer to have a comparison operator as a function, others prefer it as a member function.

By the way, the parameters must be of type const MyClass & .

+1
source

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


All Articles