C++——浅拷贝

10、深拷贝与浅拷贝

浅拷贝: 实现对象间数据元素的一一对应赋值;(默认构造函数)

深拷贝: 当被复制的对象数据成员是指针类型时,不是复制该指针成员本身,而是将指针所指的对象进行复制。

//浅拷贝

#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 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.

Copy of pointsArray1:

Point_0 of array2: 5, 10

Point_1 of array2: 15, 20

After the moving of pointsArray1:

Point_0 of array2: 25, 30

Point_1 of array2: 35, 40

Deleting...

Destructor called.

Destructor called.

Deleting...

接下来程序出现异常,也就是运行错误。出现在删除数组2的时候出错,错误原因如图:浅拷贝完成之后,两个对象指向内存的同一个地址,因此改变数组1的时候2也被改变,当释放对象内存的时候,释放1之后,2也被释放完成了,当再次释放2的时候,编译器就报错了。

posted @ 2019-01-08 11:30  lemaden  阅读(306)  评论(0编辑  收藏  举报