difference between global operator and member operator

前端 未结 5 718
一整个雨季
一整个雨季 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 13:00

    There is at least one difference. A member operator is subject to access modifiers and can be public, protected or private. A global member variable is not subject to access modifier restrictions.

    This is particularly helpful when you want to disable certain operators like assignment

    class Foo { 
      ...
    private:
      Foo& operator=(const Foo&); 
    };
    

    You could achieve the same effect by having a declared only global operator. But it would result in a link error vs. a compile error (nipick: yes it would result in a link error within Foo)

提交回复
热议问题