如何使用动态数组创建对象的Deep Copy构造函数?

这是我的代码:

类头文件:

#pragma once

class dyn_array 
{

    int totalSize;
    int numberOfElements;
    int* data;

public:

    dyn_array();

    dyn_array(const dyn_array&);

};

类cpp文件:

#include<iostream>
#include "dyn_array.h"

using namespace std;

dyn_array::dyn_array()
{

    totalSize = 4;
    numberOfElements = 0;
    data = new int[totalSize];

}

dyn_array::dyn_array(const dyn_array& copy)  
{
    totalSize = copy.totalSize;
    numberOfElements = copy.numberOfElements;
    data = new int[copy.totalSize];

    for (int i = 0; i < numberOfElements; i++)
        data[i] = copy.data[i];              //this line showing error
}

编译器向我显示以下错误:

Buffer overrun while writing to 'data': the writable size is 'copy.totalSize*4' bytes, 
but '8' bytes might be written.

我是面向对象编程的新手,请向我解释该错误,如何纠正该错误?

评论