Because the macro constants defined by # define are global and cannot be achieved, it is thought that the data members should be modified with Const. Const data members do exist, but their meaning is not what we expect. Const data members are constants only for the lifetime of an object and are mutable for the entire class, because a class can create multiple objects, and the values of its const data members can be different for different objects.
You cannot initialize a const data member in a class declaration. The following usage is incorrect, because the compiler does not know what the value of SIZE is when the object of the class is not created.
Class A
{
const int SIZE = 100; Error, attempting to initialize const data member in class declaration
int array[size]; Error, Unknown SIZE
};
The initialization of a const data member can only be done in the initialization table of the class constructor, for example
* * Variables can be initialized in the function body of the constructor function
Class A
{
A (int size); constructor function
const int SIZE;
};
A::A (int size): size (size)//constructor
{
}
A (100); Object A has a SIZE value of 100
A B (200); Object B has a SIZE value of 200
How can you build constants that are constant throughout the class? Two methods are described below:
1. The enumeration constants in the class are implemented. For example
Class A
{
enum {SIZE1 = +, SIZE2 = 200}; Enumeration constants
int ARRAY1[SIZE1];
int array2[size2];
};
Enumeration constants do not consume objects ' storage space, they are evaluated at compile time. The disadvantage of an enumeration constant is that its implied data type is an integer, its maximum value is limited, and it cannot represent a floating-point number (such as pi=3.14159).
2. Use the keyword static:
Class A
{
static const int size=100;
int array[size];
}
This creates a constant named size that will be stored with other static variables instead of being stored in an object. Therefore, this constant will be shared by all objects of the entire class.
Constants in C + + classes