The usage and problems of static in c++

Variables defined in the function, when the program is executed to its definition, the compiler allocates space for it on the stack, and the space allocated by the function on the stack will be released when the function is executed, which creates a problem : How to save the value of this variable in the function until the next call? The easiest way to think of is to define a global variable, but there are many shortcomings in defining a global variable. The most obvious shortcoming is that it destroys the access range of this variable (making the variable defined in this function not only controlled by this function ). The static keyword can solve this problem well.
In addition, in C++, a data object is required to serve the entire class instead of an object, while striving not to destroy the encapsulation of the class, that is, the member is required to be hidden inside the class, and when it is not visible to the outside, it can be defined as Static data.

Here are some of my own conclusions:
1. The static member initialization of the class needs to be defined in the global space!
For example: static class variables are declared in the .h file of the class TClass

privatestatic int aa;

After that, it must be outside the class in the .cpp file

int Tclass::aa= 1;

The way to define and assign (you can also not assign the initial value, in this case the compiler will automatically give an initial value of 0)!
Otherwise, the error of "unresolvable external symbol" will appear, as shown
Insert picture description here
in the following figure: 2. The life cycle of static member variables defined in the function body is the same as the source program (ie exe program). This feature can be used to count the number of times the function is called ,as follows:

int Tclass::countFun()
{
    
    
	static int naddCount = 0;
	naddCount++;
	return naddCount;
}
int main()
{
    
    
	Tclass t;
	cout <<"t.countFun()="<< t.countFun() << endl;
	Tclass t2;
	cout << "t.countFun()=" << t2.countFun() << endl;
	Tclass t3;
	cout << "t.countFun()=" << t3.countFun() << endl;
	Tclass t4;
	cout << "t.countFun()=" << t4.countFun() << endl;
	getchar();
    return 0;
}

The output results are:
Insert picture description here
3. The defined static class variables can be accessed through the instance of the class, or directly through the class without the instance, such as the following figure:
Insert picture description here
and we can calculate how many objects the class instantiates through the static member variables of the class , Because all class objects share the same class static member variable!

4. Static methods can only call static member variables, not non-static member variables, otherwise the compilation will report an error, as shown in the figure below:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43935474/article/details/108210533