美文网首页
浅|深 复制

浅|深 复制

作者: Vincy_ivy | 来源:发表于2019-05-31 20:16 被阅读0次

    浅复制

    //只写main函数

    int main(){
        int count;
        cout<<"Please enter the count of points:";
        cin>>count;
        ArrayOfPoints pointsArray1(cout);//count是之后element()括号里的个数
        pointArray1.element(0).move(5,10);
        pointArray1.element(1).move(15,20);
        ArrayOfPoints pointArray2=pointArray1;//创建对象副本
        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
        pointArray1.element(0).move(25,30);
        pointArray1.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; 
        return 0;
    }
    
    

    //结果是

    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
    

    我们可以看到一旦pointArray1发生了改变pointArray2也会改变,所以这是浅复制。

     
     

    深复制

    class ArrayOfPoints{
    public:
        ArrayOfPoints(const ArrayOfPoints &v);
    };
    
    ArrayOfPoints::ArrayOfPoints(const ArrayOfPoints &v){
        size=v.size;
        points=new Point[size];//相当于vector
        for(int i=0;i<size;i++){
            points[i]=v.points[i];
        } 
    }
    

    相关文章

      网友评论

          本文标题:浅|深 复制

          本文链接:https://www.haomeiwen.com/subject/rdzgtctx.html