运算符重载:仅涉及相同类型对象时的成员与非成员
Operator overload: Member vs. non-member when only same type objects can be involved
这个问题很好地回答了为什么要将运算符重载定义为非成员:Operator overloading : member function vs. non-member function?
If you define your operator overloaded function as member function,
then compiler translates expressions like s1 + s2 into
s1.operator+(s2). That means, the operator overloaded member function
gets invoked on the first operand. That is how member functions work!
But what if the first operand is not a class? There's a major problem
if we want to overload an operator where the first operand is not a
class type, rather say double. So you cannot write like this 10.0 +
s2. However, you can write operator overloaded member function for
expressions like s1 + 10.0.
现在我遇到了需要超载的情况operator==
。在我的例子中,只会比较 (a) (b) 相同 类型的对象。
是否还有理由将 operator==
定义为非成员,或者在这种情况下我应该将其实现为成员?
因为 operator==
的 LHS 和 RHS 参数具有对称语义,推荐的方法是始终根据其操作数的 public 接口将其实现为非成员(或者如果需要私有数据,以在 class).
中将其声明为好友
所以
class Bla
{
public:
// complete interface to data required for comparison
auto first();
auto second();
// ... more
private:
// data goes here
};
bool operator==(Bla const& L, Bla const& R)
{
return
std::forward_as_tuple(L.first(), L.second() /*, ... */) ==
std::forward_as_tuple(R.first(), R.second() /*, ... */)
;
}
这样,L 和 R 参数都考虑了到 Bla
的隐式转换(我并不是说隐式转换是个好主意,但如果你有这些,最好避免出现意外情况它们仅被考虑用于 RHS 参数。
这个问题很好地回答了为什么要将运算符重载定义为非成员:Operator overloading : member function vs. non-member function?
If you define your operator overloaded function as member function, then compiler translates expressions like s1 + s2 into s1.operator+(s2). That means, the operator overloaded member function gets invoked on the first operand. That is how member functions work!
But what if the first operand is not a class? There's a major problem if we want to overload an operator where the first operand is not a class type, rather say double. So you cannot write like this 10.0 + s2. However, you can write operator overloaded member function for expressions like s1 + 10.0.
现在我遇到了需要超载的情况operator==
。在我的例子中,只会比较 (a) (b) 相同 类型的对象。
是否还有理由将 operator==
定义为非成员,或者在这种情况下我应该将其实现为成员?
因为 operator==
的 LHS 和 RHS 参数具有对称语义,推荐的方法是始终根据其操作数的 public 接口将其实现为非成员(或者如果需要私有数据,以在 class).
所以
class Bla
{
public:
// complete interface to data required for comparison
auto first();
auto second();
// ... more
private:
// data goes here
};
bool operator==(Bla const& L, Bla const& R)
{
return
std::forward_as_tuple(L.first(), L.second() /*, ... */) ==
std::forward_as_tuple(R.first(), R.second() /*, ... */)
;
}
这样,L 和 R 参数都考虑了到 Bla
的隐式转换(我并不是说隐式转换是个好主意,但如果你有这些,最好避免出现意外情况它们仅被考虑用于 RHS 参数。