字符串strcpy函数的实现,已经字符串string的实现,编写构造函数,拷贝构造函数,赋值函数,析构函数
赋值函数注意四个步骤:
1、检查自赋值情况
2、释放掉原有内存
3、分配新的内存
4、返回*this
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
char* myStrCpy(char *strDest, const char *strSrc)
{
assert((strDest!=NULL) && (strSrc!=NULL));//注意判断指针为空
char *strAddr=strDest;
while ((*strDest++ = *strSrc++)!='\0')
;
return strAddr;//返回char *类型,目的是为了实现链式表达式,myStrCpy(str1, myStrCpy(str2, str3))
}
class MyString
{
public:
MyString();
MyString(const char *str);
MyString(const MyString &other);
MyString& operator=(const MyString &other);
~MyString();
private:
char *m_data;//类中含有指针数据成员,一定要自己实现构造、复制构造、赋值、析构函数
};
MyString::MyString()
{
m_data=new char[1];
m_data='\0';
}
MyString::MyString(const char *str)
{
if (str==NULL)
{
m_data=new char[1];
m_data='\0';
}
else
{
int len=strlen(str);
m_data = new char[len+1];//加1是加上'\0'占的一个字节
strcpy(m_data,str);
}
}
MyString& MyString:: operator=(const MyString &other)
{
if (this==&other)
{
return *this;
}else
{
delete m_data;//赋值操作时,类已经存在,赋值前要先擦出原有内存,再重新分配内存
m_data=new char[strlen(other.m_data)+1];
if (m_data!=NULL)
{
myStrCpy(m_data,other.m_data);
}
return *this;
}
}
MyString::MyString(const MyString &other)
{
/**拷贝构造函数为什么不用先删除内存?
既然是拷贝构造,那么该对象还没有生成,因此不需要像赋值操作那样先执行删除操作
**/
m_data=new char[strlen(other.m_data)+1];
if (m_data!=NULL)
{
strcpy(m_data,other.m_data);
}
}
MyString::~MyString()
{
if (m_data!=NULL)
{
delete m_data;
}
}
int main()
{
char *strSrc="hello world";
MyString mystr("hello world");
MyString mystr1(strSrc);
MyString mystr2(mystr);
MyString mystr3;
mystr3=mystr;
return 0;
}