#2
东海ECS2023-04-24 18:53
|
程序代码:
class hstring
{
private:
unsigned short usmlen{}; //新建的内存长度
char* cstr; //字符串
unsigned short uslen; //字符串长度
unsigned short getlength(const char* str); //得到对象的字符串长度
void copystr(char*& dest, const char* source); //复制内存函数
public:
hstring(const char* _str);
hstring(const hstring& hstr);
hstring& operator=(const hstring& str);
const hstring operator()(unsigned short start,unsigned short length);
~hstring();
//hstring& operator= (const char* str);
char* getstr()
{
return cstr;
}
};
hstring::hstring()
{
cstr = nullptr;
usmlen = 0x32;
}
unsigned short hstring::getlength(const char* str)
{
unsigned short len{};
for (; str[len]; len++);
return len;
}
void hstring::copystr(char*& dest, const char* source)
{
unsigned short len = getlength(source);
if (len > usmlen)
{
delete cstr;
dest = new char[len + 1]; //重新分配内存
usmlen = len;
}
uslen = len;
dest = new char[0x32];
memcpy(dest, source, usmlen);
}
hstring::hstring(const char* _str) :hstring()
{
copystr(cstr, _str);
}
hstring::hstring(const hstring& hstr) : hstring()
{
copystr(cstr, hstr.cstr);
}
hstring& hstring::operator=(const hstring& hstr)
{
copystr(cstr, hstr.cstr);
return *this;
}
const hstring hstring::operator()(unsigned short start, unsigned short length)
{
if (start > uslen - 1)
{
return hstring(" ");
}
//unsigned short strlen{};
//strlen = start + length > uslen - 1 ? uslen - 1 - start : length;
//char* newcstr = new char[strlen+1];
char* newcstr = new char[length + 1];
memcpy(newcstr, cstr+start, length+1);
return hstring(newcstr);
}
int main()
{
hstring hstr1="54321";
hsring hstr2=hstr1(0,2);
std::cout<<hstr2;
}
这里应该输出54,但是输出了 54还有两个乱码,有没有前辈知道怎么回事