Since the macro constants defined by #define are global and cannot achieve their goal, I take it for granted that const should be used to modify data members. const data members do exist, but their meaning is not what we expect. const data memberIt is a constant only during the lifetime of an object, but is mutable for the entire class, because the class can create multiple objects, and 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 wrong 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 const data members can only be performed in the initialization table of the class constructor, for example
**Variables can be initialized in the body of the constructor
class A
{
A(int size); // Constructor
const int SIZE ;
};
A::A(int size) : SIZE(size) // Constructor
{
}
A a(100); // The SIZE value of object a is 100
A b(200); // The SIZE value of object b is 200
How can we build constants in the entire class? The following two methods are introduced:
1. Use enumeration constants in the class to implement it. For example
class A
{
enum { SIZE1 = 100, SIZE2 = 200}; // Enumeration constants
int array1[SIZE1];
int array2[SIZE2];
};
Enumeration constants do not occupy the storage space of objects, and they are all evaluated at compile time. The disadvantage of enumeration constants is that its implicit data type is an integer, its maximum value is limited, and it cannot represent floating point numbers (such as PI=3.14159).
2. Use keywordsstatic:
class A
{
static const int SIZE=100;
int array[SIZE];
}
This creates a constant called SIZE, which will be stored with other static variables, rather than in some object. Therefore, this constant will be shared by all objects of the entire class.
Note: This technique can only be used to declare static constants with integers or enumerations, and cannot store double-type constants.