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();

word...合計の長さではなく、1 の長さだけを出力しました。

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 に答える