C++——動態內存分配2-創建對象數組


//創建對象數組

#include<iostream>

using namespace std;

class Point

{ public:

       Point()

      {   X=Y=0;     cout<<"Default Constructor called."<<endl;     }

       Point(int xx,int yy)

      {   X=xx;     Y=yy;     cout<< "Constructor called."<<endl;     }

       ~Point()

      {   cout<<"Destructor called."<<endl;    }

       int GetX() {return X;}

       int GetY() {return Y;}

          void Move(int x,int y)

                   {  X=x;  Y=y;   }

  private:

       int  X,Y;

};

 

int main()

{

     Point *Ptr=new Point[2];    //創建對象數組

     Ptr[0].Move(5,10);     //通過指針訪問數組元素的成員

     Ptr[1].Move(15,20);   //通過指針訪問數組元素的成員

     cout<<"Deleting..."<<endl;

     delete[ ] Ptr;               //刪除整個對象數組

}//運行結果:

Default Constructor called.

Default Constructor called.

Deleting...

Destructor called.

Destructor called.

//動態數組類,不需要預先設計好數組的大小

#include<iostream>

using namespace std;

class Point

{ public:

       Point()

      {   X=Y=0;     cout<<"Default Constructor called."<<endl;     }

       Point(int xx,int yy)

      {   X=xx;     Y=yy;     cout<< "Constructor called."<<endl;     }

       ~Point()

      {   cout<<"Destructor called."<<endl;    }

       int GetX() {return X;}

       int GetY() {return Y;}

          void Move(int x,int y)

                   {  X=x;  Y=y;   }

  private:

       int  X,Y;

};

class ArrayOfPoints

{

   public:

     ArrayOfPoints(int n)//根據實際來調整數組大小

     {   numberOfPoints=n;  points=new Point[n];  }

     ~ArrayOfPoints()//

     {   cout<<"Deleting..."<<endl;

         numberOfPoints=0;  delete[] points;     }

     Point& Element(int n)//返回所需要的元素

     {  return points[n];  }

   private:

     Point *points;

     int numberOfPoints;

};

 

int main()

{

         int number;

         cout<<"Please enter the number of points:";

         cin>>number;

     ArrayOfPoints points(number);    //創建對象數組

     points.Element(0).Move(5,10);     //通過指針訪問數組元素的成員

     points.Element(1).Move(15,20);   //通過指針訪問數組元素的成員

}

//運行結果如下:

Please enter the number of points:2

Default Constructor called.

Default Constructor called.

Deleting...

Destructor called.

Destructor called.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM