You can also use operator new to create an object of the array type, and you need to give the structure description of the arrays. The syntax for dynamically creating a one-dimensional array with the new operator is:
New type name "array Length";
The length of the array indicates the number of elements in the array, which can be any expression that can get a positive integer value.
Details:
When you create a one-dimensional array dynamically with new, you can still enclose the parentheses "()" after the square brackets, but you cannot take any arguments inside the parentheses. The difference between adding "()" is that, without "()", the initialization of each element of the array is the same as when the "new T" is executed, and "()" is the same as the execution of "new T ()". For example, if you generate an integer array dynamically:
int *p=new int[10] ();
It is convenient to initialize the dynamically created array with 0 values.
In the case of an array created with new, use Delete to delete the pointer name preceded by "" ", the format is as follows:
delete[] pointer name;
#include <iostream>using namespace STD;classpoint{ Public: Point (): X (0), Y (0) {cout<<"default constructor called."<<endl; } Point (intXintY): X (x), Y (y) {cout<<"constructor called."<<endl; } ~point () {cout<<"destructor called."<<endl; }intGetx ()Const{returnx;}intGety ()Const{returnY;}voidMovee (intNEWX,intNewy) {x=newx; Y=newy; }Private:intx, y;};intMain () {point *ptr=Newpoint[2];//Create an array of objectsptr[0].movee (5,Ten);//Access the members of an array element through pointersptr[1].movee ( the, -);//Access the members of an array element through pointers cout<<"Deleting ..."<<endl;Delete[] ptr;//Delete an entire array of objects return 0;}
The dynamic memory allocation operation is used to create the dynamic array, so that the number of elements in the array can be determined according to the needs of the runtime. However, the process of creating and deleting arrays makes the program a little cumbersome, and a better way is to encapsulate the creation and deletion of arrays to form a dynamic array class.
The next article has an introduction to the dynamic array class.
Creating arrays Dynamically