c++: Difference between member and non member functions

前端 未结 6 904
一整个雨季
一整个雨季 2020-12-12 20:35

What is the difference between member and non-member functions in C++?

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 21:22

    A non-static member function is invoked on objects of the class it belongs to. It has implicitly access to the this pointer representing the current object. Through this pointer, it may access other members easily and with full access privileges (i.e. access private members).

    A non-member function has no implicit this. In the sample below, bar is a member function while freebar is not. Both do more or less the same, but note how bar gets an implicit object pointer via this (also only bar has privileged access to foo's members, freebar only has access to public members).

    class foo {
    public:
    
        void bar() {
            this->x = 0; // equivalent to x = 0;
        }
    
        int x;
    };
    
    void freebar(foo* thefoo) {
       thefoo->x = 1;
    }
    
    
    // ... 
    foo f;
    f.bar();
    // f.x is now 0
    
    freebar(&f);
    // f.x is now 1
    

    Semantically a member function is more than just a function with an implicit this parameter. It is meant to define the behaviour of an object (i.e. a car object would have drive(), stop() as member functions).

    Note that there are also static member functions which have full privileges but don't get an implicit this nor are they invoked through an instance of the class (but rather through the full name of the class).

提交回复
热议问题