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

    {

    //同前例

    }

  • 相关阅读:
    Spring经典视频教程大集合
    使用jsonlib进行Java和JSON之间的转换
    c:import Unable to get RequestDispatcher for Context
    打开IE都会弹出欢迎界面“欢迎使用Internet Explorer 8”
    Struts2 标签 用法示例 (
    as3相关的frameworks
    as相关的框架引擎应用集合
    init
    XNA框架基础——疑难解答
    XNA框架基础——XNA的注意事项
  • 原文地址:https://www.cnblogs.com/gary-guo/p/6230035.html
Copyright © 2020-2023  润新知