0
点赞
收藏
分享

微信扫一扫

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时调用的是默认的拷贝构造函数,实现对应数据项的直接复制。其过程如下,

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

对象的深拷贝

#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()
{
//同前例
}

举报

相关推荐

0 条评论