Consider the following class:
class A { void foo() { static int i; i++; } };
When dealing with static variables within member functions in C , it is crucial to understand how they behave across instances.
Multiple Instances and Static Variables
Contrary to the assumption that each instance would possess its own copy of the static variable, in this specific scenario, there will be only one copy of static int i within the entire program. This is because class A is a non-template class, and A::foo() is a non-template function.
Instance Impact on Static Variable
Regardless of which instance of A invokes the foo() method, the shared static variable i will be affected. For instance, if you declare multiple instances of A like this:
A o1, o2, o3;
Calling foo() on any of these instances will increment the i variable:
o1.foo(); // i = 1 o2.foo(); // i = 2 o3.foo(); // i = 3 o1.foo(); // i = 4
In conclusion, static variables in member functions are shared across all instances of the class, allowing any instance to access and modify the same value.
The above is the detailed content of How do static variables in member functions behave across different instances of a class?. For more information, please follow other related articles on the PHP Chinese website!