Possible Duplicate:
Overload operators as member function or non-member (friend) function?
在学习 C++ 运算符重载的过程中,我看到了两种不同类型的重载运算符 +。
我需要您的帮助来告诉我哪种方法更好: 方法一:
Complex Complex::operator + (Complex &obj) {
return Complex( re + obj.re, im + obj.im );
}
方法二:
Complex operator + (const Complex &obj1, const Complex &obj2) {
// this function is friend of class complex
return Complex(obj1.re + obj2.re, obj1.im + obj2.im);
}
谢谢!!!
最佳答案
只要不能出现隐式转换,两者都同样好;
这更多的是一个品味问题。如果可以隐式转换为
复杂
(在这种情况下似乎是可能的),然后使用第一种形式,
隐式转换仅适用于第二个参数,例如:
Complex c;
Complex d;
d = c + 1.0; // Works in both cases...
d = 1.0 + c; // Only works if operator+ is free function
在这种情况下,免费功能是迄今为止的首选解决方案;许多 由于正交性的原因,人们更喜欢系统地使用它。
事实上,在许多这样的情况下,自由函数operator+
将是
根据operator+=
(将成为成员)实现:
Complex
operator+( Complex const& lhs, Complex const& rhs )
{
Complex results( lhs );
results += rhs;
return results;
}
事实上,提供模板基类相当简单
它自动提供所有这些运算符。 (在这种情况下,
他们被声明为 friend
,以便在
模板基类。)
关于c++ - 使用什么代码更好地进行运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10172222/