Define static variables in member functions

Source: Internet
Author: User

Define static variables in member functions

The local variables in the member functions can be static. If you define a local variable in a member function as a static variable, all objects in the class will share the variable when calling this member function.

Example 3-40

 

In this example, a static variable S is defined in the member function M. Because S is defined in the block, it has the block range, so it can only be accessed within M. S is added each time M is called. Because M is a member function of C, all objects in C share this static local variable. In this way, each call to M accesses the same S. On the contrary, for non-static local variable X, each c object has an X. Therefore, in Main, call c1.m () for the first time to increase s from 0 to 1, call c2.m () to increase s from 1 to 2, and call c2.m () for the second time () increase s from 2 to 3.

 

In addition:

This variable exists until the end of the program and is not re-generated every call. Static variables in the function are a good implementation method in singleton mode.

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.