non-static vs. static function and variable

前端 未结 4 1527
無奈伤痛
無奈伤痛 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;
    
    
    }
    
    0 讨论(0)
  • 2021-02-04 13:56

    For this, you need to understand what is static.

    Static data members exist once for the entire class, as opposed to non-static data members, which exist individually in each instance of a class. They will have a class scope and does not bound to an instance of the class.

    To access static member of the class, we use the format as below ::

    if you have created 10 objects of a class. Assume, you were able to access the non-static variable in the static member of the class, When the static function is called, which object's member it needs to change?

    0 讨论(0)
  • 2021-02-04 13:57

    Static means this is independent of a particular instance of the class. Static methods don't have access to the this pointer. That is the reason you need to call them using the class name.

    When you call the Static method, you might not even have any instance of the class defined.

    non-static means implies an instance, and could be different with different instances.

    So, basically, it does not make sense to access non-static members from static methods.

    0 讨论(0)
  • 2021-02-04 13:57

    It's not ok. Static functions are accessible without having an instance of a class and thus can't access information that you would need an instance to determine.

    For example, you don't need a car to know how many wheels it has, blueprints for a general car would suffice (that could be static information) but you can't tell what color the car is unless you're referring to a specific car (that information needs a specific instance of an object.)

    0 讨论(0)
提交回复
热议问题