The variables defined in the static function are not shared by all objects, the static variables of the class and the global variables outside the class, and the difference between static and normal functions.

Source: Internet
Author: User

A static member of a class, which is shared by all objects, is allocated at the start of the process, and is then fixed without allocating space.

The difference between a static member variable of a class and a global variable outside the class is that you can set an access flag to allow only object access to the class. If you define static variables for public in a class, then there is no difference between a global variable and a class.

And what about the variables defined in a static member function of a class? Is it also shared by all objects?
The static function of a class is the same as a member variable of a class, and it is when the process executes that the control is assigned to the code at the outset, and then provides a function's address entry for all objects or other code calls, and static functions are not allowed to invoke the class's normal variables. You can only access static variables for a class. Because it does not get the this pointer to the object. The advantage of static function is that it can be invoked directly with the class name dot, without having to allocate space to generate an instance object.

Each time the static function is invoked, the process also presses it into the stack and allocates a space within the stack for the variables defined in the static function, each time the static function is invoked, the local variable of the static function is assigned.

So the variables defined in the static function are independent,

What if a static variable is defined in a static function? The fact tells us that static variables are not allowed to be defined in static functions. Because it makes no sense, since you want all objects and functions to share that variable, it's OK to define it as a static variable for the class.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.