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的时候,编译器就报错了。

转载于:https://www.cnblogs.com/lemaden/p/10238039.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值