完整的错误消息:
抛出异常:写入访问冲突。
this->数据为0x1110116。
我的代码:
#include <iostream>
#include <new>
class SimpleSet {
public:
/** Construct empty set **/
SimpleSet()
{
data = new int[8];
currentSize = 0;
maxSize = 8;
}
/** Destructor */
~SimpleSet()
{
delete[] data;
data = nullptr;
}
/** Insert i into set, return true if the element was inserted, else false **/
bool insert(int i)
{
if (find(i) == -1)
{
++currentSize;
if (currentSize == maxSize)
{
try // Return 0 if array can't be increased.
{
int* temp = new int[maxSize += maxSize];
for (int j = 0; j < currentSize; ++j)
{
temp[j] = data[j];
}
temp[currentSize] = i;
delete[] data;
data = temp;
return 1;
}
catch(std::bad_alloc& ba)
{
return 0;
}
}
else
{
data[currentSize] = i; // THIS IS LINE 51!
return 1;
}
}
else
{
return 0;
}
}
/** Returns true if i is in the set **/
bool exists(int i)
{
return ((find(i) == -1) ? 0 : 1);
}
/** Removes i from the set, return true if an element was removed **/
bool remove(int i)
{
if (find(i) != -1)
{
for (int j = find(i); j < currentSize - 1; ++j)
{
data[j] = data[j + 1];
data[currentSize--] = NULL;
}
return 1;
}
else
{
return 0;
}
}
private:
/** Dynamic array containing set elements **/
int *data;
/** Current number of elements **/
int currentSize;
/** Max capasity of data **/
int maxSize;
/** Returns the index where i may be found, else an invalid index. **/
int find(int i)
{
int index = -1;
for (int j = 0; j < currentSize; ++j)
{
if (i == j)
{
std::cout << "Found element in set\n";
return j;
}
}
return index;
}
};
当我尝试向SimpleSet添加元素时,我得到了错误。在第51行。
非常感谢任何帮助。
编辑:主文件。
int main()
{
SimpleSet testSet;
testSet.insert(0);
std::cout << testSet.exists(0) << std::endl;
return 0;
}
编辑:
重新启动的视觉工作室,现在它可以工作..对不起麻烦..