4-数组、指针与字符串1.5-深拷贝与浅拷贝

默认的拷贝构造函数并不总是适宜的,因为它完成的只是浅拷贝。

eg:对象的浅拷贝

#include<iostream>

using namespace std;

class Point

{

  //类的定义

}

class ArrayOfPoints

{

  //类的定义

}

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;

}

程序中pointsArray2是从pointsArray1复制过来的,他们的初始状态是一样的,但是当程序通过move函数对pointsArray1中的第一组点进行移动之后,pointsArray2中的第二组点也被移动到了同样的位置,这说明这两组点存在某种必然的联系,而这种联系并不是我们所期望的。

这里建立对象pointsArray2时调用的是默认的拷贝构造函数,实现对应数据项的直接复制。其过程如下,

对象的深拷贝

#include<iostream>

using namespace std;

class Point

{

  ...//类的定义

};

class ArrayOfPoints

{

  public:

  ArrayOfPoints(ArrayOfPoints &pointsArray);//拷贝构造函数

};

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()

{

//同前例

}

 

转载于:https://www.cnblogs.com/gary-guo/p/6230035.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值