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

后端 未结 1 2018
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 23:03

In C++, i know there are two ways to overload. We can overload it inside (like class a) or outside (like class b). But, the question is, is there any d

相关标签:
1条回答
  • 2021-02-03 23:49

    The member operator+ requires the LHS to be an a - The free operator requires LHS or RHS to be a b and the other side to be convertible to 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+
    
    }
    
    0 讨论(0)
提交回复
热议问题