Operator overloading : member function vs. non-member function?

后端 未结 2 890
無奈伤痛
無奈伤痛 2020-11-22 04:50

I read that an overloaded operator declared as member function is asymmetric because it can have only one parameter and the other parameter passed automatically is

2条回答
  •  猫巷女王i
    2020-11-22 05:19

    It's not necessarily a distinction between friend operator overloads and member function operator overloads as it is between global operator overloads and member function operator overloads.

    One reason to prefer a global operator overload is if you want to allow expressions where the class type appears on the right hand side of a binary operator. For example:

    Foo f = 100;
    int x = 10;
    cout << x + f;
    

    This only works if there is a global operator overload for

    Foo operator + (int x, const Foo& f);

    Note that the global operator overload doesn't necessarily need to be a friend function. This is only necessary if it needs access to private members of Foo, but that is not always the case.

    Regardless, if Foo only had a member function operator overload, like:

    class Foo
    {
      ...
      Foo operator + (int x);
      ...
    };
    

    ...then we would only be able to have expressions where a Foo instance appears on the left of the plus operator.

提交回复
热议问题