12 January 2019

C++ How to dynamically create an array of objects

 #include "stdafx.h"  
 #include <iostream>  
 using namespace std;  
 class Point  
 {  
 public:  
      int x; int y;  
      Point(int _x, int _y)  
      {  
           x = _x;  
           y = _y;  
           cout << "Point constructor:(" << x << "," << y << ")" << endl;  
      }  
      ~Point()  
      {  
           cout << "Point destructor:(" << x << "," << y << ")" << endl;  
      }  
 };  
 std::ostream& operator<< (std::ostream& stream, const Point& p) {  
      return stream << "(" << p.x << "," << p.y << ")" << endl;  
 }  
 double* CreateDoubles()  
 {  
      double* d = new double[3];  
      d[0] = 1.1;  
      d[1] = 2.2;  
      d[2] = 3.3;  
      return d;  
 }  
 Point** CreatePoints()  
 {  
      Point** p = new Point*[2];  
      p[0] = new Point(1, 2);  
      p[1] = new Point(3, 4);  
      return p;  
 }  
 void Test()  
 {  
      double* d = CreateDoubles();  
      cout << "Dynamically created doubles: " << d[0] << ", " << d[1] << ", " << d[2] <<endl <<endl;  
      delete[] d;  
      Point** p = CreatePoints();  
      cout << "Dynamically created Points: " << endl;  
      cout << *p[0] << endl;  
      cout << *p[1] << endl;  
      delete p[0];  
      delete p[1];  
      delete[] p;  
 }  
 int main()  
 {  
      Test();  
      getchar();  
   return 0;  
 }  

No comments:

Post a Comment