C ++运算符==重载 [英] C++ operator== overloading
问题描述
可能重复:
操作员超载
Possible Duplicate:
Operator overloading
以下重载operator ==的方式之间有什么区别?
What is the differences between the following ways to overload operator== ?
// stroustrup way
friend bool operator== (MyClass &lhs, MyClass &rhs);
和
// as taught in other places, including caltech
bool MyClass::operator== (MyClass &rhs);
哪种方法更好?
推荐答案
// stroustrup way
friend bool operator== (MyClass &lhs, MyClass &rhs);
参数应为const
:
friend bool operator==(const MyClass& lhs, const MyClass& rhs);
这是首选方法,因为它可以在隐式构造第一个参数时起作用.例如,如果std::string
仅具有成员函数operator==
,则"abc" == my_std_string
不会调用它!但是,可以通过从"abc"隐式构造一个字符串来调用非成员函数(更好的是,在这种情况下,出于性能原因可以提供单独的bool operator==(const char*, const std::string&)
,但要点仍然存在-非成员函数可以帮助确保操作员在两侧使用用户定义的类型.
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.
最后一点:如果没有其他方法可以访问需要比较的数据,则只需将非成员operator==
设置为friend
.否则,您可以在类外部声明/定义它,如果希望将实现包含在最终可能链接到同一可执行文件的多个翻译单元中,则可以选择内联.虽然危害不大,但让它成为朋友是将定义放入类模板的唯一方法,在该类模板中,您不必重复模板"的内容和参数....
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....
这篇关于C ++运算符==重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!