String class = operator

时间:2012-11-29 21:20:55

标签: c++ string substring

我正在构建自己的字符串类,我在使用子字符串

时遇到了一些麻烦
// 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;
}

我无法弄清楚我做错了什么,谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

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

只用长度做新的:

char* result = new char[length];

编辑:

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

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

result[i] = '\0';

答案 1 :(得分:1)

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

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

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

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

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

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

相关问题