Dynamic object array creation

// Dynamically build object features:
/****
	1. The variable or object bit heap object created and released during the running of the program is completed by the new and delete operators respectively.
	2. The heap dynamic object is a controllable object with a lifetime and can be deleted at any time.
	3. Dynamically apply for an array of objects, the object must have a default constructor or the leftmost formal parameter of the constructor must have a default value
***/
#include <iostream>
using namespace std;
class point
{
public :
	//Dynamic construction of an array of objects must have a default constructor, or a constructor with default parameters
	point(){
	}
	 //point(int i=0, int j=0 )
	 point(int i, int j )
	 {
		 x=i ; y=j ;
		 cout<<"constructor called."<<endl;
	 }
	 ~point()
	 {
		 cout<<"destruct called. "<<endl;
	 }
	 int getx()
{
   return x;
}
	 int gety ()
{  
return y;
}
 private:
	 int x, y;
};
intmain()
{
	point *PA1, *PA2;
	PA1=new point(1,2); // Dynamically create an object, call the constructor, and assign initial values ​​1, 2
	PA2= new point(3,4); // Dynamically create an object, call the constructor, and assign initial values ​​3, 4
	cout<<PA1->getx()<<","<<PA1->gety()<<endl;
	cout<< PA2->getx()<<","<<PA2->gety()<<endl;
	delete PA1; // undo the dynamic object PA1, automatically call the destructor
	delete PA2; // undo the dynamic object PA2, automatically call the destructor
	point *PA=new point[2];// Dynamically create an array of objects, call the constructor twice, use the default value of the parameter
	cout<<PA[0].getx()<<","<<PA[0].gety()<<endl;
	delete[ ] PA; // delete the object array, automatically call the destructor twice
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326359758&siteId=291194637