Problem with homegrown Concat method
I've implemented my own String
class, and need to write Concat
method.
I can't get it work.
My code is:
//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;
}
The problem in the Conc开发者_开发知识库at
method is that I wrote something like:
String word3 = word1.Contact(word2);
It is supposed to make word3
to be like word1+word2
but the program failed when I ran it.
When I wrote:
cout << word1.Contact(word2).Length();
...it printed only the word
1's length, instead of the combined length.
Let's examine the following code:
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];
}
Look at your loop condition, then look at your if condition. Clearly the else block will never execute, and your string is never concatenated.
To fix this problem, your loop condition should be replaced with needed_length
. Then you would have to replace string[index]
with string[index - original_str_size]
to get the correct index in string
.
Your code should look like this:
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];
}
On a side note, what does str_copy
point to? Is it valid memory? Did del()
free the memory? Might want to check that.
In the your Concat function, it looks like you are deleting the memory which contains your original string before copying the string out of that memory into the newly allocated memory.
In Compare, you have a ; after the for loop, this means the loop does nothing. Also you are returning 0 when the first character matches.
In Concat, you are making str_copy = m_str, then presumably deleting m_str and creating a new m_str. then you copy from the deleted m_str to the new m_str, you may get lucky, but I would not rely on this.
精彩评论