我正在尝试自己定义C ++中的字符串类,仅用于练习,在定义追加函数时,我得到以下错误:
HEAP CORRUPTION DETECTED:正常块CRT检测到应用程序在堆缓冲区结束后写入内存。
休息时间是我尝试在"删除[] aPtr"中删除内存。 这是我的代码:
私人成员:int len,cap; char * aPtr;
String::String() //default constructor
{
len = 0;
cap = 1;
aPtr = new char[1];
aPtr[0] = '\0';
}
String::String(const String &original) //copy constructor
{
if (cap < original.len)
{
char *t;
cap*=2;
len = original.len;
t = new char[cap];
for (int i = 0;i < len + 1;i++) //copy
{
t[i] = original.aPtr[i];
}
delete[] aPtr;
aPtr = t;
}
else
{
len = original.len;
for (int i = 0;i < len + 1;i++) //copy
{
aPtr[i] = original.aPtr[i];
}
}
}
String & String::operator=(const String &original) // = overload
{
if (*this != original) //Check if string = string
{
if (cap < original.len)
{
char *t;
len = original.len;
cap *= 2;
t = new char[cap];
for (int i = 0;i < len + 1;i++) //copy
{
t[i] = original.aPtr[i];
}
delete[] aPtr;
aPtr = t;
}
else
{
len = original.len;
for (int i = 0;i < len + 1;i++) //copy
{
aPtr[i] = original.aPtr[i];
}
}
}
return *this;
}
void String::append(const String &str)
{
char *temp;
int newLen = len + str.len;
if (cap < newLen + 1)
{
cap = 2 * newLen;
temp = new char[cap];
for (int i = 0;i < len;i++)
{
temp[i] = aPtr[i];
}
for (int i = 0; i < str.len + 1;i++)
{
temp[len + i] = str.aPtr[i];
}
delete [] aPtr;
aPtr = temp;
len = newLen;
}
else
{
for (int i = 0; i < str.len + 1;i++)
{
aPtr[len + i] = str.aPtr[i];
}
}
}
感谢任何帮助!