Create
InC ++Allows dynamic creationConstObject in the following format:
Const int * P = new const int (128 );
Like other constantsConstThe object must be initialized at creation and its value cannot be changed after initialization.
Delete
Although it cannot be changedConstObject value, but can delete dynamically createdConstObject in the following format:
Delete P;
Like a common object, you can delete it.
ApplicationScenarioExample 1Load the configuration file
The data read from the configuration file can be used for initialization.ConstObject for laterProgram.
PseudoCodeAs follows:
Int num;
...//Read the configuration file and fill in the configuration dataNum
Const int * pnum = new const int (Num );//UseNumInitializationConstObject
Cout <* pnum <Endl ;//UseConstObject
...
Delete pnum;
2, Create an array
When the array size depends on some dynamic factors (such as configuration files), you can consider usingConstObject.
The pseudocode is as follows:
Int num;
...//ObtainNumValue
Const int * pnum = new const int (Num );//UseNumInitializationConstObject
Unsigned char _ DATA [* pnum]; //Create an array
...
Delete pnum
The sample code is as follows:
# Include <iostream> Using Namespace STD; Int Main (){ Int Num; CIN > Num; Const Int * Pnum = New Const Int (Num ); Int Arr [* Pnum]; For ( Int I =0 ; I <* pnum; ++ I) Arr [I] = I; For ( Int I = 0 ; I <* pnum; ++ I) cout <arr [I] < " " ; Cout < Endl; Return 0 ;}
Of course, there are many other scenarios. I have thought of these for the moment. I will record them here for future reference.