C ++ const data member
A member constant modified by const. The memory address of this constant is in the constant area. If the value of the member constant is determined after the structure of the object. That is, the constant belongs to an object.
Static modified static variables are also stored in the static storage area. It belongs to a class rather than a specific object. This value can be changed. The initialization of this value is completed in the compilation phase.
Note that the const member variable Initialization is in the const initialization list rather than in the const body. It also occupies memory.
One problem is where the static const modified member constants are stored. It must be understood that the constant belongs to the class and cannot be changed.
I have discussed on the internet whether the definition of this constant can be included in the header file.
This problem depends on your compiler version. Early compilers do not allow initialization in class declarations.
Most of the current versions are supported.
It is understandable that the compiler does not support static variables. Static variables must be declared outside the class.
The const variable must be initialized during definition. Static does not belong to a specific class.
So this is easy to understand. The compiler does not support strict calligraphy checks.
This is not in line with the code writing specifications. The definition is better in the. c file.
Memory Allocation of const constants (basic type)
If you define a global constant,
Const int constant = 3333333;
No memory allocation
If you only assign this constant value to other variables, this constant does not occupy the memory. This is like a macro definition. But it is safer than macro definition because there is a type check.
Allocate memory
1 const member variable, as mentioned above.
2 extern const int constant = 3333; if you define a constant in a file, it is internally visible and cannot be used like a global variable in other files.
To use it in other files, the declaration must be displayed as extern. After such declaration, allocate memory space for the constant.
3 const int constant = 3333;
Const int * pconstant = & constant;
Constants cannot be defined after they are declared.