对于我使用C ++编写的一个编程类,我们需要设计一个布尔数组类,包括带有内存分配的长度和布尔数组,我收到错误消息-线程0x4c0c已退出,代码为0(0x0)。引发异常:读取访问冲突。这是nullptr。
当我尝试使用changeLength方法创建新数组时出现:
布尔数组H文件
#ifndef BOOL_ARRAY_H
#define BOOL_ARRAY_H
class boolArray
{
public:
boolArray() { array = { NULL }; length = 0; }
boolArray(int len);//setting new array according users input
void intialize(int len);//setting new array according users input
void changeLength(int len);//create new array with new length
private:
bool validIndex(int index);//check if the number is in the relevant range
bool* array;
int length;
};
#endif
布尔数组CPP文件
boolArray::boolArray(int len)
{//ctor with parameter
if (validIndex(len))//checking if the length is a valid number
intialize(len);//set the new array
}
void boolArray::intialize(int len)
{//setting new array according users input
length = len;//initialize length from user
array = new bool[length];//memory allocation
if (!array)//check if memory allocation succeeded
{
cout << "memory allocation failed!" << endl;//show message
return;//go back
}
for (int i = 0; i < length; i++)
array[i] = 0;//set all cells false
}
void boolArray::changeLength(int len)
{//create new array with new length
if (length!=0)//if array exists //ERROR HERE
delete[] array;//free memory
intialize(len);//set new array
}
bool boolArray::validIndex(int index)
{//check if the number is in the relevant range
if (index >= 0 && index <= length)
return true;//if it is returns true
else//if not in the range
cout << "please enter a valid number!" << endl;//message
return false;//return false
}
主要使用布尔数组类别---
boolArray* array;
int len;//new array length
cout << "enter size of array " << endl;
cin >> len;
array->changeLength(len);
谢谢!
array = new bool(length);//memory allocation
您的意思是new bool[length]
。
array
为空。可能是奶奶家附近的一切,因为您忘记了对其进行初始化并将其指向boolArray
的有效实例。 boolArray* array; // uninitialized pointer
int len;//new array length
cout << "enter size of array " << endl;
cin >> len;
array->changeLength(len); // Crom only knows what array points at.
最直接的解决方案是根本不使用指针
boolArray array; // no need for a pointer here int len;//new array length cout << "enter size of array " << endl; cin >> len; array.changeLength(len);
但我希望
int len;//new array length cout << "enter size of array " << endl; cin >> len; boolArray array(len); // no need to resize.
然后,您需要修复David Schwartz突出显示的错误-这是远远不够的-而且这个错误:
boolArray::boolArray(int len) {//ctor with parameter if (validIndex(len)) //there is no length to validate against. // It hasn't been set yet. intialize(len); }
在构建数组之前检查数组访问的长度没有用,因此我将其删除。
boolArray::boolArray(int len) {//ctor with parameter intialize(len); }
以及警告:此类未遵守the Rule of Three,因此不能安全地复制。