0

我已经实现了自己的String类,需要编写Concat方法。

我无法让它工作。

我的代码是:

//the m_str is private member which is initialize in the c-tor
//this function is get a string and concat it with the original string
String &String::Concat(const char *string)
{
    int original_str_size = length(m_str);
    int other_str_size = length(string);
    int needed_length = original_str_size + other_str_size + 1;

    char *str_copy = m_str;

    del();

    m_str = new char[needed_length];
    m_size = needed_length;

    int index = 0;

    for(; index < original_str_size; index++)
    {
        if(index < original_str_size)
            m_str[index] = str_copy[index];
        else
            m_str[index] = string[index];
    }

    m_str[index] = 0;

    return *this;
}

Concat方法的问题是我写了类似的东西:

String word3 = word1.Contact(word2);

它应该word3是这样word1+word2的,但是当我运行它时程序失败了。

当我写道:

cout << word1.Contact(word2).Length();

...它只打印word1 的长度,而不是组合长度。

4

3 回答 3

1

让我们检查以下代码:

int index = 0;
for(; index < original_str_size; index++)
{
    if(index < original_str_size)
        m_str[index] = str_copy[index];
    else
        m_str[index] = string[index];
}

查看您的循环条件,然后查看您的 if 条件。显然 else 块永远不会执行,并且您的字符串永远不会连接。

要解决此问题,您的循环条件应替换为needed_length. 然后你必须用 替换string[index]string[index - original_str_size]获得正确的索引string

您的代码应如下所示:

int index = 0;
for(; index < needed_length; index++)
{
    if(index < original_str_size)
        m_str[index] = str_copy[index];
    else
        m_str[index] = string[index - original_str_size];
}

在旁注中,str_copy指向什么?它是有效的记忆吗?del()释放内存了吗?可能想检查一下。

于 2011-05-24T20:12:54.813 回答
0

在您的 Concat 函数中,看起来您正在删除包含原始字符串的内存,然后将字符串从该内存复制到新分配的内存中。

于 2011-05-24T19:46:45.473 回答
0

在比较中,您有一个 ; 在 for 循环之后,这意味着循环什么也不做。当第一个字符匹配时,您也将返回 0。

在 Concat 中,您正在制作 str_copy = m_str,然后可能会删除 m_str 并创建一个新的 m_str。然后你从删除的 m_str 复制到新的 m_str,你可能会很幸运,但我不会依赖这个。

于 2011-05-24T19:39:42.833 回答