C++ static member functions and variables

前端 未结 6 480
北恋
北恋 2021-01-31 11:40

I am learning C++ by making a small robot simulation and I\'m having trouble with static member functions inside classes.

I have my Environment class defined like this:<

6条回答
  •  耶瑟儿~
    2021-01-31 12:02

    static members are those that using them require no instantiation, so they don't have this, since this require instantiation:

    class foo {
    public
        void test() {
            n = 10; // this is actually this->n = 10
        }
        static void static_test() {
            n = 10; // error, since we don't have a this in static function
        }
    private:
        int n;
    };
    

    As you see you can't call an instance function or use an instance member inside an static function. So a function should be static if its operation do not depend on instance and if you require an action in your function that require this, you must think why I call this function static while it require this.

    A member variable is static if it should shared between all instances of a class and it does not belong to any specific class instance, for example I may want to have a counter of created instances of my class:

    // with_counter.h
    class with_counter {
    private:
        static int counter; // This is just declaration of my variable
    public:
        with_counter() {++counter;}
        ~with_counter() {--counter;}
    
        static int alive_instances() {
            // this action require no instance, so it can be static
            return counter;
        }
    };
    
    // with_counter.cpp
    int with_counter::counter = 0; // instantiate static member and initialize it here
    

提交回复
热议问题