在类内部或外部重载操作符有什么区别?

what is the difference between overloading an operator inside or outside a class?

本文关键字:什么 区别 操作符 重载 内部 外部      更新时间:2023-10-16

在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;
}

成员operator+要求LHS为a -自由运算符要求LHS RHS为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+
}