1.编写类String的构造函数,析构函数和赋值函数,已知类String用成员变量char* _str
来保存字符串
//普通的构造函数
String::String(const char* str)
{
if(str == NULL)
{
_str = new char[1];//对空字符串自动申请存放‘\0’的空间
*_str = '\0';
}
else
{
int length = strlen(str);
_str = new char[length+1];//若能加NULL判断则更好
strcpy(_str,str);
}
}
//String 的析构函数
String::~String(void)
{
delete[]_str;
}
//拷贝构造函数
String::String(const String &other)//输入参数为const型
{
int length = strlen(other._str);
_str = new char[length+1];//对_str加NULL 判断
strcpy(_str,other._str);
}
//赋值函数
String & String::operate = (const String &other)
{
if(this ==&other)
{
return *this;
}
delete[]_str;
int length = strlen(other._str);
_str = new char[length+1];
strcpy(_str,other._str);
return *this;
}
2.c语言的strcpy函数
char * strcpy(char*strDest,const char*strSrc)
{
assert((strDest!NULL)&&(strSrc!=NULL));
char*address= strDest;
while((*strDest++=*strSrc++)!='\0')NULL;
return address;
}

被折叠的 条评论
为什么被折叠?



