C++ operator== overloading

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?


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


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)


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.

链接地址: http://www.djcxy.com/p/12708.html

上一篇: 我执行++增量运算符时遇到问题

下一篇: C ++运算符==重载