运行时错误:使用类时调试断言失败

时间:2015-10-20 19:01:58

标签: debugging c++ runtime-error

我正在为我的大学C ++课中的作业编写代码,该程序旨在使用类创建动态分配的数组。当我的对象超出范围时,我得到一个调试断言失败错误,因为我双删除指向新创建的数组的指针。我不知道发生了什么,因为我只在整个班级中使用了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;
}

确切错误的屏幕截图: enter image description here

1 个答案:

答案 0 :(得分:0)

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