Where would you use a friend function vs. a static member function?

后端 未结 15 2218
[愿得一人]
[愿得一人] 2020-12-02 04:56

We make a non-member function a friend of a class when we want it to access that class\'s private members. This gives it the same access rights as a static member function w

15条回答
  •  春和景丽
    2020-12-02 05:21

    • One reason to prefer a friend over static member is when the function needs to be written in assembly (or some other language).

      For instance, we can always have an extern "C" friend function declared in our .cpp file

      class Thread;
      extern "C" int ContextSwitch(Thread & a, Thread & b);
      
      class Thread
      {
      public:
          friend int ContextSwitch(Thread & a, Thread & b);
          static int StContextSwitch(Thread & a, Thread & b);
      };
      

      And later defined in assembly:

                      .global ContextSwitch
      
      ContextSwitch:  // ...
                      retq
      

      Technically speaking, we could use a static member function to do this, but defining it in assembly won't be easy due to name mangling (http://en.wikipedia.org/wiki/Name_mangling)

    • Another situation is when you need to overload operators. Overloading operators can be done only through friends or non-static members. If the first argument of the operator is not an instance of the same class, then non-static member would also not work; friend would be the only option:

      class Matrix
      {
          friend Matrix operator * (double scaleFactor, Matrix & m);
          // We can't use static member or non-static member to do this
      };
      

提交回复
热议问题