浅|深 复制

2019-05-31  本文已影响0人  Vincy_ivy

浅复制

//只写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];
    } 
}
上一篇下一篇

猜你喜欢

热点阅读