Sometimes we want some constants to be valid only in the class. Since the macro constants defined by # define are global and cannot be achieved, it is assumed that we should use const to modify data members. The const data member does exist, but its meaning is not what we expected. The const data member is a constant only within the lifetime of an object, but it is variable for the entire class, because the class can create multiple objects, the values of the const data members of different objects can be different.
The const data member cannot be initialized in the class declaration.The following usage is incorrect because the compiler does not know what the size value is when the class object is not created.
Class
{...
Const int size = 100; // error, attempted to initialize the const data member in the class declaration
Intarray [size]; // error, unknown size
};
The const data member initialization can only be performed in the initialization table of the class constructor, for example
Class
{...
A (INT size); // Constructor
Const int size;
};
A: A (INT size): size (size) // initialization table of the constructor
{
...
}
A A (100); // the size of object A is 100
A B (200); // the size of object B is 200
How can we create constants that are constant throughout the class? Don't count on the const data member. We should use the enumerated constants in the class. For example
Class
{...
Enum {size1 = 100, size2 = 200}; // enumerated constant
Int array1 [size1];
Int array2 [size2];
};
Enumerated constants do not occupy the storage space of objects. They are fully evaluated during compilation. The disadvantage of an enumerated constant is that its implicit data type is an integer, its maximum value is limited, and it cannot represent a floating point number (such as Pi = 3.14159 ).