difference between global operator and member operator

前端 未结 5 712
一整个雨季
一整个雨季 2020-12-02 12:43

Is there a difference between defining a global operator that takes two references for a class and defining a member operator that takes only the right operand?

Glob

5条回答
  •  春和景丽
    2020-12-02 12:53

    One reason to use non-member operators (typically declared as friends) is because the left-hand side is the one that does the operation. Obj::operator+ is fine for:

    obj + 2
    

    but for:

    2 + obj
    

    it won't work. For this, you need something like:

    class Obj
    {
        friend Obj operator+(const Obj& lhs, int i);
        friend Obj operator+(int i, const Obj& rhs);
    };
    
    Obj operator+(const Obj& lhs, int i) { ... }
    Obj operator+(int i, const Obj& rhs) { ... }
    

提交回复
热议问题