[C ++ deep analysis learning summary] 25 types of static member variables
Author CodeAllen , please indicate the source
1. Member Variables
- Can access public member variables by object name
- The member variables of each object are unique
- Member variables cannot be shared between objects
2. New demand
- Count the number of objects of a certain class during the running of the program
- Ensure the safety of the program (global variables cannot be used)
- The number of current objects can be obtained at any time
Solution attempt (failed solution)
#include <stdio.h>
class Test
{
private:
int mCount;
public:
Test() : mCount(0)
{
mCount++;
}
~Test()
{
--mCount;
}
int getCount()
{
return mCount;
}
};
Test gTest;
int main()
{
Test t1;
Test t2;
printf("count = %d\n", gTest.getCount());
printf("count = %d\n", t1.getCount());
printf("count = %d\n", t2.getCount());
return 0;
}
3. Static member variables-start to introduce new concepts
in C + + can define static member variables
- Static member variables belong to the entire class
- The lifetime of static member variables does not depend on any objects
- You can directly access public static member variables by class name
- Static member variables of all objects sharing classes
- Public static member variables can be accessed by object name
Characteristics of static member variables
- Modified directly by the static keyword at the time of definition
- Static member variables need to be allocated separately outside the class
- Static member variables are located in the global data area inside the program
Grammar rules:
- Type ClassName::VarName = value;
Use of static member variables
#include <stdio.h>
class Test
{
private:
static int cCount;
public:
Test()
{
cCount++;
}
~Test()
{
--cCount;
}
int getCount()
{
return cCount;
}
};
int Test::cCount = 0; //需要在类的外部单独定义,隶属于test
Test gTest;
int main()
{
Test t1;
Test t2;
printf("count = %d\n", gTest.getCount());
printf("count = %d\n", t1.getCount());
printf("count = %d\n", t2.getCount());
Test* pt = new Test(); //指向堆上的一个指针对象,动态生成,触发构造函数就 ++,输出为4
printf("count = %d\n", pt->getCount());
delete pt;
printf("count = %d\n", gTest.getCount());
return 0;
}
Summary
Static member variables can be defined through the static key in a class.
Static member variables belong to all classes.
Every object can access static member variables.
Static member variables are allocated in the global data area
. The life time of static member variables is the program runtime.