C++——深拷貝

要實現深拷貝就須要本身編寫拷貝構造函數。ios

深拷貝數組

#include<iostream>函數

using namespace std;spa

class Point指針

{ public:對象

       Point()ci

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

       Point(int xx,int yy)class

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

       ~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(ArrayOfPoints& pointsArray);

     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;

};

ArrayOfPoints ::ArrayOfPoints(ArrayOfPoints& pointsArray)//本身寫拷貝構造函數,用本類對象的引用做參數

{   numberOfPoints=pointsArray.numberOfPoints;

    points=new Point[numberOfPoints];

    for (int i=0; i<numberOfPoints; i++)

      points[i].Move(pointsArray.Element(i).GetX(),pointsArray.Element(i).GetY());

}

int main()

{

         int number;

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

         cin>>number;

     ArrayOfPoints pointsArray1(number);    //建立對象數組

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

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

     ArrayOfPoints pointsArray2(pointsArray1); //建立對象數組副本

     cout<<"Copy of pointsArray1:"<<endl;

     cout<<"Point_0 of array2: "

         <<pointsArray2.Element(0).GetX()

         <<", "<<pointsArray2.Element(0).GetY()<<endl;

     cout<<"Point_1 of array2: "

         <<pointsArray2.Element(1).GetX()

         <<", "<<pointsArray2.Element(1).GetY()<<endl;

     pointsArray1.Element(0).Move(25,30);     //經過指針訪問數組元素的成員

     pointsArray1.Element(1).Move(35,40);   //經過指針訪問數組元素的成員

     cout<<"After the moving of pointsArray1:"<<endl;

     cout<<"Point_0 of array2: "

         <<pointsArray2.Element(0).GetX()

         <<", "<<pointsArray2.Element(0).GetY()<<endl;

     cout<<"Point_1 of array2: "

         <<pointsArray2.Element(1).GetX()

         <<", "<<pointsArray2.Element(1).GetY()<<endl;

} //程序的運行結果以下:

Please enter the number of points:2

Default Constructor called.           

Default Constructor called.

Default Constructor called.

Default Constructor called.

Copy of pointsArray1:

Point_0 of array2: 5, 10

Point_1 of array2: 15, 20

After the moving of pointsArray1:

Point_0 of array2: 5, 10

Point_1 of array2: 15, 20

Deleting...

Destructor called.

Destructor called.

Deleting...

Destructor called.

Destructor called.

相關文章
相關標籤/搜索