Run-time error: Debug Assertion Failed when using Classes

Run-time error: Debug Assertion Failed when using Classes

我正在为大学 C++ class 中的作业编写代码,该程序旨在使用 class 创建一个动态分配的数组。当我的对象超出范围时,我收到调试断言失败错误,因为我双重删除了指向新创建数组的指针。我不知道这是在哪里发生的,因为我在整个 class 中只使用了两次 delete[]。这是我的来源: #include

using namespace std;

//classes
class IntArray {
private:
int * begin;
int arrSize;

//returns true if n is a valid index inside the array
bool inBounds(int n) {
    if (n < 0 || n >= arrSize) {
        return false;
    }
    return true;
}
public:
//default constructor
IntArray() {
    begin = new int[1];
    begin[0] = 0;
    arrSize = 1;
}

//call constructor
IntArray(int n) {
    arrSize = n;
    begin = new int[n];

    for (int i = 0; i < n; i++) {
        begin[i] = 0;
    }

}

//copy constructor
IntArray(IntArray * in) {
    arrSize = in->size();
    begin = new int[arrSize];

    for (int i = 0; i < arrSize; i++) {
        begin[i] = in->begin[i];
    }
}

//call constructor for arrays
IntArray(int in[],int s) {
    arrSize = s;
    begin = new int[arrSize];

    for (int i = 0; i < arrSize; i++) {
        begin[i] = in[i];
    }
}

//method functions

//returns the size of the array
int size() {
    return arrSize;
}

//returns the value of the element at position n
int get(int n) {
    if (inBounds(n)) {
        return begin[n];
    }

    cout << "Error: Invalid bound entered, returning value at index 0" << endl;
    return begin[0];
}

//function that sets the value at position n to the value of input
void put(int n, int input) {
    if (inBounds(n)) {
        begin[n] = input;
    }
    else {
        cout << "Error: invalid bound entered, no value changed" << endl;
    }
}

//overloaded operators

//sets the value at the position n to input value
int & operator[](int n) {
    if (inBounds(n)) {
        return begin[n];
    }
    cout << "Error: invalid bound entered, returning index 0" << endl;
    return begin[0];
}

//operator = allows copying of one IntArray to another
IntArray & operator=(IntArray source) {
    arrSize = source.size();
    delete[] begin;
    begin = 0;

    begin = new int[arrSize];

    for (int i = 0; i < arrSize; i++) {
        begin[i] = source[i];
    }

    return *this;
}

//destructor
~IntArray() {
    //deallocate memory used by array
    if (begin != 0) {
        delete[] begin;
    }
}


};

int main() {
IntArray arr1(10);

for (int i = 0; i < 10; i++) {
    arr1[i] = 11 * i;
    cout << arr1[i] << " ";
}
cout << endl;

for (int i = 0; i < 10; i++) {
    cout << arr1.get(i) << " ";
}
cout << endl;

arr1.put(6, 16);
arr1.put(4, 10);

IntArray arr2(arr1);

IntArray arr3 = arr1;

for (int i = 0; i < 10; i++) {
    cout << arr3.get(i) << " ";
}
cout << endl;

for (int i = 0; i < 10; i++) {
    cout << arr2.get(i) << " ";
}
cout << endl;


system("PAUSE");

return 0;
}

以及具体错误的截图:

感谢@heavyd,我意识到错误是由于 class 定义中的逻辑错误导致 class 的不正确构造引起的。问题在于我将数据复制到新 class 的方式(不正确)和我的复制构造函数的工作方式,以及我的一个成员函数的 return 类型。