在类内部或外部重载运算符有什么区别?

Ali*_*232 27 c++ operator-overloading

在C++中,我知道有两种方法可以重载.我们可以在内部(如类a)或外部(如类b)重载它.但是,问题是,这两者在编译时或运行时是否存在差异?

class a
{
public:
    int x;
    a operator+(a p) // operator is overloaded inside class
    {
        a temp;
        temp.x = x;
        temp.x = p.x;
        return temp;
    }
};

class b
{
public:
    friend b operator+(b, b);
    int x;
};

b operator+(b p1, b p2) // operator is overloaded outside class
{
    p1.x += p2.x;
    return p1;
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*rik 24

该成员operator+要求LHS成为a- 免费运营商要求LHS RHS成为a b,而另一方可转换为b

struct Foo {
    Foo() {}
    Foo(int) {}
    Foo operator+(Foo const & R) { return Foo(); }
};


struct Bar {
    Bar() {}
    Bar(int) {}
};

Bar operator+(Bar const & L, Bar const & R) {
    return Bar();
}


int main() {
    Foo f;
    f+1;  // Will work - the int converts to Foo
    1+f;  // Won't work - no matching operator
    Bar b;
    b+1;  // Will work - the int converts to Bar
    1+b;  // Will work, the int converts to a Bar for use in operator+

}
Run Code Online (Sandbox Code Playgroud)

  • 这似乎表明在类外部重载运算符总是更好。但事实是这样吗? (2认同)