This article illustrates the method of implementing a Const object dynamically by C + +. Share to everyone for your reference. The specific methods are analyzed as follows:
First, create
In C + +, the const object is allowed to be created dynamically in the following format:
const INT *P = new const int (128);
As with other constants, dynamically created const objects must be initialized at creation time, and their values cannot be changed after initialization.
Second, delete
Although you cannot change the value of a const object, you can delete the dynamically created const object in the following format:
This is the same as a normal object and can be deleted.
Iii. Examples of application scenarios
1. Load configuration file
Data that is read from the configuration file can be used to initialize the const object for use by subsequent programs.
Pseudo code is as follows:
int num;
Read the configuration file and populate the configuration data to num
const INT *pnum = new const int (num);//Initialize the const object with num
cout<<*pnum<< Endl Use const object
...
Delete Pnum;
2. Create an array
When the size of an array depends on some dynamic factors (such as configuration files), you can consider using the const object.
Pseudo code is as follows:
int num;
...//Get NUM's value
const INT *pnum = new const int (num);/////////////////////////////////////////
5/>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;
}
There are, of course, a lot of other scenes, which are recorded here for the time being and convenient for later inspection.
I hope this article will help you with the C + + program design.