字符串类 = 运算符

String class = operator

本文关键字:运算符 字符串      更新时间:2023-10-16

我正在努力构建自己的字符串类,但在使用子字符串时遇到了一些问题

// 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;
}

文本是字符串类的数据成员。我收到一个未处理的异常,访问冲突读取位置。

当我调试它正在经历这些过程时

// 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;
}

我不知道我做错了什么,谢谢你的帮助。

考虑使用 char* 构造函数创建 String 对象时会发生什么情况:

String::String(const char* text){
  *this = text;
}

尚未初始化任何成员,并且您调用operator=

String& String::operator = (const char* text){
  // Delete the existing string first
  delete[] Text;

删除成员Text,即使尚未初始化它。删除单位化指针会产生未定义的行为。在这种情况下,行为是一个例外。

在调用 operator= 之前,要么在构造函数中将Text初始化为 null,要么在构造函数中执行所有工作,而不是赋值运算符。

当你分配length-startPosition时,你很可能使用负数。

只用长度做新的:

char* result = new char[length];

编辑:

i=0开始复制,并将最后一个复制字符后面的字节设置为 null:

for(int i=0; i<length; i++)
    result[i] = Text[i+startPosition];
result[i] = '';