C + + Implementation Dynamic Allocation Const object Instance _c language

Source: Internet
Author: User

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:

Delete p;

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.