non-static vs. static function and variable

前端 未结 4 1519
無奈伤痛
無奈伤痛 2021-02-04 12:55

I have one question about static and non-static function and variable.

1) non-static function access static variable.

It\'s OK!

class Bar
{
publ         


        
4条回答
  •  北海茫月
    2021-02-04 13:44

    static function access non-static variable

    It's OK or not OK? I am puzzled about this!

    When called, a static function isn't bound to an instance of the class. Class instances (objects) are going to be the entities that hold the "non-static" variables. Therefore, from the static function, you won't be able to access them without actually being passed or storing elsewhere a specific instance to operate on.

    So yes, the code in your last example is valid, because you are passed in an instance. However, you could not do:

    static void staticFunction()
    {
        // error, this function is static, and is therefore
        // not bound to a specific instance when called
        i = 5;
    
    
    }
    

提交回复
热议问题