我正在构建自己的字符串类,但在子字符串方面遇到了一些问题
// Substring operator
// reutns a substring from a given point
String String::Substring(int startPosition, int length) const{
if(length==0)
length = GetLength()+1; //Takes care of null terminator, im not worried about if length is imputed yet
char* result = new char[length-startPosition]; // Assume it's not negative for the sake of just getting it to work, It would only be negative if it's user error
for(int i=startPosition; i<length; i++)
result[i] = Text[i]; //Since it will always go from a given point to the end, the null terminator will transfer in the for loop.
return result;
}
Text 是字符串类的数据成员。我得到一个未处理的异常,访问冲突读取位置。
当我调试时,它正在经历这些过程
// Init-constructor for initializing this string with a C-string
String::String(const char* text){
*this = text;
}
和
// Assigns C-string to this String
String& String::operator = (const char* text){
// Delete the existing string first
delete[] Text;
// +1 accounts for null terminator
int trueLength = GetLength(text)+1;
// Allocate new memory
Text = new char[trueLength];
// Copy all characters from source into Text
for ( int i = 0; i < trueLength; i++)
Text[i] = text[i];
return *this;
}
我无法弄清楚我做错了什么,感谢您的帮助。