64,651
社区成员
发帖
与我相关
我的任务
分享
String::String( const char* str )
{
//add code here..
//要判断原字符串是否为空
if(str == NULL)
{
mData = new char[1];
*mData = '\0';
mLength = 0;
}
else
{
int buff_size = strlen(str);
mLength = buff_size;
mData = new char[buff_size + 1];
//strncpy()比strcpy()更安全
strncpy(mData,str,buff_size);
mData[buff_size] = '\0'; //此处去掉+1,只改这一个地方就可以了
}
}
void String::reverse()
{
//add code here...
String temp(*this);
int i;
mData = new char[temp.mLength + 1];
mLength = temp.mLength;
for(i = 0; i < temp.mLength; ++i)
{
mData[i] = temp.mData[temp.mLength - i - 1];
}
mData[mLength] = '\0';
}
String String::operator +(const String &str )
{
//add code here...
//这里需要注意加运算并不改变操作数
String temp(*this);
int i;
temp.mData = new char[this->mLength + str.mLength + 1];
for(i = 0; i < this->mLength; ++i)
{
temp.mData[i] = this->mData[i];
}
for(i = 0; i < str.mLength; ++i)
{
temp.mData[this->mLength + i] = str.mData[i];
}
temp.mData[this->mLength + str.mLength] = '\0';
temp.mLength = this->mLength + str.mLength;
return temp;
}
String::String( const char* str )
{
//add code here..
//要判断原字符串是否为空
if(str == NULL)
{
mData = new char[1];
*mData = '\0';
mLength = 0;
}
else
{
int buff_size = strlen(str);
mLength = buff_size;
mData = new char[buff_size + 1];
//strncpy()比strcpy()更安全
strncpy(mData,str,buff_size);
mData[buff_size + 1] = '\0';//此处越界访问,应为mData[buff_size] = '\0'
}
}
const String::size_t & String::size() const
{
//add code here...
return mLength;
}
void String::copyfromotherstring( const String& str )
{
//add code here...
for(int i = 0; i < str.mLength; ++i)
{
mData = new char[1];
this->mData = str.mData;
}
this->mLength = str.mLength;
}
String& String::operator =(const String & str )
{
copyfromotherstring(str);
return *this;
}
String::String( const char* str )
{
//add code here..
//要判断原字符串是否为空
if(str == NULL)
{
mData = new char[1];
*mData = '\0';
mLength = 0;
}
else
{
int buff_size = strlen(str);
mLength = buff_size;
mData = new char[buff_size + 1];
//strncpy()比strcpy()更安全
strncpy(mData,str,buff_size);
mData[buff_size + 1] = '\0';
}
}
——最后一句,不应该加1。