Introduction to constants in C++ classes

  • 2020-04-02 01:46:26
  • OfStack

Since the macro constants defined by #define are global and do not serve the purpose, it is assumed that they should be implemented using const to decorate the data members. Const data members do exist, but their meaning is not what we expect. Const data member Is constant only for the lifetime of an object, but is mutable for the entire class, because the class can create multiple objects, and different objects can have different values for their const data members.

Const data members cannot be initialized 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 a const data member in a class declaration
  int array[SIZE];  //Error, unknown SIZE
}; 

Initialization of const data members can only occur in the initialization table of the class constructor, for example
** variables can be initialized in the body of a constructor

class A 
{
  A(int size);  //The constructor
  const int SIZE ;    
}; 
A::A(int size) : SIZE(size)  //constructional
{ 
} 
A  a(100); //The SIZE value of object a is 100
A  b(200); //The SIZE value of object b is 200

How do you set up constants that are constant throughout the class? The following two methods are described:

1. Use the enumeration constants in the class to implement. For example,


class A 
{
  enum { SIZE1 = 100, SIZE2 = 200}; //Enumerated constants
  int array1[SIZE1];  
  int array2[SIZE2]; 
}; 

Enumeration constants do not take up the storage space of an object, they are all evaluated at compile time. The disadvantage of enumerating 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 keywords Static:


class A
{
 static const int SIZE=100;
 int array[SIZE];
}

This creates a constant called SIZE, which is stored with other static variables instead of in an object. Therefore, this constant is Shared by all objects in the entire class.

Note: you can only use this technique to declare static constants whose values are integers or enumerations, not to store constants of type double.


Related articles: