uacs2024

导航

郑莉cpp例6-22 浅层复制与深层复制 动态数组类?动态类数组类?

浅层复制与深层复制

浅层复制并没有形成真正的副本,存在两个对象共用同一块内存空间而导致执行析构函数时,该空间被两次释放,导致运行错误。

深层复制则实现,复制之后,两个对象不互相影响。

#include <iostream>
using namespace std;
#include <cassert>

class Point{
public:
    Point():x(0),y(0)   {cout << "Default Constructor called." << endl;}
    Point(int x,int y):x(x),y(y)    {cout << "Constructor called." << endl;}
    ~Point()    {cout << "Destructor called." << endl;}
    int getX() const    {return x;}
    int getY() const    {return y;}
    void move(int newX,int newY)    {x = newX;y = newY;}
private:
    int x,y;
};

class ArrayOfPoints{
public:
    ArrayOfPoints(int size):size(size)    {points = new Point[size];}
    ~ArrayOfPoints() {
        cout << "Deleting..." << endl;
        delete[] points;
    }

    Point &element(int index) {
        assert(index >= 0 && index < size);
        return points[index];
    }

    ArrayOfPoints(const ArrayOfPoints &v);

private:
    Point *points;
    int size;
};

ArrayOfPoints::ArrayOfPoints(const ArrayOfPoints &v)
{
    size = v.size;
    points = new Point[size];
    for(int i = 0;i < size;i++)
    {
        points[i] = v.points[i];
    }
}

int main()
{
    int count;
    cout << "Please enter the count of points:";
    cin >> count;
    ArrayOfPoints pointsArray1(count);
    pointsArray1.element(0).move(5,0);
    pointsArray1.element(1).move(15,20);

    cout << "-------------------------" << endl;

    ArrayOfPoints pointsArray2 = pointsArray1;
    cout << "Copy of pointsArrayl : " << endl;
    cout << "Point_0 of array2 : " << pointsArray2.element(0).getX() << " , " << pointsArray2.element(0).getY() << endl;
    cout << "Point_l of array2 : " << pointsArray2.element(1).getX() << " , " << pointsArray2.element(1).getY() << endl;

    cout << "-------------------------" << endl;

    pointsArray1.element(0).move(25,30);
    pointsArray1.element(1).move(35,40);
    cout << "After the moving of pointsArrayl : " << 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;
}

结果

Please enter the count of points:2
Default Constructor called.
Default Constructor called.
-------------------------
Default Constructor called.
Default Constructor called.
Copy of pointsArrayl :
Point_0 of array2 : 5 , 0
Point_l of array2 : 15 , 20
-------------------------
After the moving of pointsArrayl :
Point_0 of array2 : 5 , 0
Point_1 of array2 : 15 , 20
Deleting...
Destructor called.
Destructor called.
Deleting...
Destructor called.
Destructor called.

 

posted on 2024-03-10 17:13  ᶜʸᵃⁿ  阅读(5)  评论(0编辑  收藏  举报