C++ operator== overloading [duplicate]

2019-06-16 21:16发布

Possible Duplicate:
Operator overloading

What is the differences between the following ways to overload 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?

3条回答
放荡不羁爱自由
2楼-- · 2019-06-16 21:20
// stroustrup way
friend bool operator== (MyClass &lhs, MyClass &rhs);

Arguments should be const:

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

This is preferred as it works when the first argument can be implicitly constructed. For example, if std::string only had a member function operator==, then "abc" == my_std_string would not invoke it! But, the non-member function can be invoked by implicitly constructing a string from "abc" (better yet in this particular case, a separate bool operator==(const char*, const std::string&) can be provided for performance reasons, but the point still stands - non-member functions can help ensure the operator works with the user-defined-type on either side).

Separately, implicit constructors are a bit dangerous - and you want to think hard about the convenience versus danger of using them.

A final point: you only need to make the non-member operator== a friend if there's no other way to access the data you need to compare. Otherwise, you can declare/define it outside the class, optionally inline if you want the implementation in a header that may be included from multiple translation units eventually linked into the same executable. Not much harm though, and making it a friend is the only way to put the definition inside a class template, where you don't have to repeat the "template " stuff and parameters....

查看更多
Ridiculous、
3楼-- · 2019-06-16 21:22

First is external friend function (free function)

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

Second is member function

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

You should use second variant always then you can

You should use first variant in case: 1) First argument is the external (library) class

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

2) Operator's logic not related to your class and must be implemented separately

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

(because your class can't know all about classes that may need in compare operator)

查看更多
Explosion°爆炸
4楼-- · 2019-06-16 21:32

This :

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

is a function, which compares two objects.

This :

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

is a member function.

You should use the one proposed by your coding standard, or use the one you prefer. None is better. Some people (including myself) prefer to have the comparison operator as a function, other prefer it as a member function.

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

查看更多
登录 后发表回答