我已经实现了自己的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 的长度,而不是组合长度。