1

可能重复:
将运算符重载为成员函数或非成员(朋友)函数?

在学习 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);
}

谢谢!!!

4

2 回答 2

4

As long as there can be no implicit conversions, both are equally good; it's more a matter of taste. If there can implicit conversions to Complex (which in this case seems likely), then with the first form, implicit conversions will only work on the second argument, e.g.:

Complex c;
Complex d;

d = c + 1.0;    //  Works in both cases...
d = 1.0 + c;    //  Only works if operator+ is free function

In such cases, the free function is by far the preferred solution; many people prefer it systematically, for reasons of orthogonality.

In many such cases, in fact, the free function operator+ will be implemented in terms of operator+= (which will be a member):

Complex
operator+( Complex const& lhs, Complex const& rhs )
{
    Complex results( lhs );
    results += rhs;
    return results;
}

In fact, it's fairly straightforward to provide a template base class which provides all of these operators automatically. (In this case, they're declared friend, in order to define them in line in the template base class.)

于 2012-04-16T10:30:53.803 回答
1

Bjarne Stroustrup 建议您使用第二种形式,用于不修改对象本身或根据提供的参数生成新值/对象的情况。

于 2012-04-16T10:20:34.573 回答