The mechanics of extension via free functions or member functions

后端 未结 5 941
挽巷
挽巷 2021-02-14 12:45

Loads of C++ libraries, the standard included, allow you to adapt your objects for use in the libraries. The choice is often between a member function or a free function in the

5条回答
  •  灰色年华
    2021-02-14 13:12

    Altought, sometimes, developers can used free functions or class functions, interchangeably, there are some situations, to use one another.

    (1) Object / Class functions ("methods), are prefered when most of its purpouse affect only the object, or objects are inteded to compose other objects.

    // object method
    MyListObject.add(MyItemObject);
    MyListObject.add(MyItemObject);
    MyListObject.add(MyItemObject);
    

    (2) Free ("global" or "module") functions are prefered, when involves several objects, and the objects are not part / composed of each other. Or, when the function uses plain data (structs without methods, primitive types).

    MyStringNamespace.MyStringClass A = new MyStringNamespace.MyStringClass("Mercury");
    MyStringNamespace.MyStringClass B = new MyStringNamespace.MyStringClass("Jupiter"); 
    // free function
    bool X = MyStringNamespace.AreEqual(A, B);
    

    When some common module function access objects, in C++, you have the "friend keyword" that allow them to access the objects methods, without regarding scope.

    class MyStringClass {
      private:
        // ...
      protected:
        // ...
      // not a method, but declared, to allow access
      friend:
        bool AreEqual(MyStringClass A, MyStringClass B);
    }
    
    bool AreEqual(MyStringClass A, MyStringClass B) { ... }
    

    In "almost pure object oriented" programming languages like Java or C#, where you can't have free functions, free functions are replaced with static methods, which makes stuff more complicated.

提交回复
热议问题