我正在编写一个动态数组类。我包含了一个复制构造函数和 operator= 函数,以允许我将一个数组分配给另一个数组。当我将相同长度的数组相互分配时它可以工作,但是当它们具有不同的长度时,我会收到编译器内存警告和/或代码炸弹而不执行,具体取决于左侧数组是否大于右侧数组,反之亦然。我有一个向数组插入值的函数,并认为问题可能出在此处(注意:我必须注释掉析构函数中的内存删除才能使代码运行)。
class Array
{
private:
int * ptr;
int size;
int numElement;
public:
Array();
Array(const int*, int);
Array(const Array&);
~Array();
void setValueAtIndex(int, int);
void insertValueAtEnd(int );
int getArraySize();
const Array& operator=(const Array& );
};
#include "array.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
Array::Array()
{
size = 10;
numElement = 0;
ptr = new int[size];
for (int i = 0; i < size; ++i)
{
ptr[i] = 0;
}
}
Array::Array(const int * ptr_, int size_)
{
size = size_;
numElement = size;
ptr = new int[numElement];
for (int i = 0; i < size; ++i)
{
ptr[i] = ptr_[i];
}
}
Array::Array(const Array& other)
{
size = other.size;
numElement = other.numElement;
if (other.ptr)
{
ptr = new int[numElement];
for(int i = 0; i < size; ++i)
{
ptr[i] = other.ptr[i];
}
if(!ptr)
{
exit(EXIT_FAILURE);
}
}
else ptr = 0;
}
Array::~Array()
{
if(ptr)
{
//delete [] ptr;
//ptr = 0;
}
}
void Array::setValueAtIndex(int a, int b)
{
if(b > size)
{
exit(EXIT_FAILURE);
}
ptr[b] = a;
}
void Array::insertValueAtEnd(int insert)
{
if(numElement == size)
{
size++;
}
ptr[size-1] = insert;
numElement++;
}
int Array::getArraySize()
{
return size;
}
const Array& Array::operator=(const Array& other)
{
if(this != &other)
{
if (ptr)
{
delete [] ptr;
ptr = 0;
}
numElement = other.numElement;
size = other.size;
if(other.ptr)
{
ptr = new int[numElement];
for(int i = 0; i < size; ++i)
{
ptr[i] = other.ptr[i];
}
}
else ptr = 0;
}
return *this;
}