字符串strcpy函数的实现,以及字符串string的实现,编写构造函数,拷贝构造函数,赋值函数,析构函数

字符串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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值