【发布时间】:2015-10-21 09:55:52
【问题描述】:
我正在为我的大学 C++ 课程中的作业编写代码,该程序旨在使用一个类创建一个动态分配的数组。当我的对象超出范围时,我收到调试断言失败错误,因为我双重删除了指向新创建数组的指针。我不知道这发生在哪里,因为我在整个班级中只使用了两次 delete[]。这是我的来源: #包括
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;
}
【问题讨论】:
-
你试过在调试器中运行它吗?在您调用
delete的两个地方放置断点并进行调试。 -
请注意,您的复制构造函数不是defined correctly。
-
@heavyd 我已经通过调试器运行它,当调用析构函数并尝试删除已删除的动态分配数组时会出现问题。至于复制构造函数,当我尝试使用 const IntArray & 时,它不会让我使用指针表示法或其他我知道如何使用的表示法。
-
当你引用一个对象(即
const IntArray &)时,你可以只使用点符号。我提到复制构造函数错误的原因是,当你构造arr2和arr3时,你实际上并没有调用你认为的构造函数(在那里放一个断点,你会看到它永远不会命中)。 -
我尝试使用点表示法,它说'对象具有与成员函数对象类型不兼容的类型限定符:const IntArray'
标签: debugging c++ runtime-error