自定义string类

    自定义一个简化版本的string类,其中成员函数包括:(1)构造函数。(2)赋值构造函数。(3)赋值操作符(=)。(4)重载操作符([])。(5)比较函数。(6)析构函数。非成员函数只有重载操作符<<(定义为友源函数)。数据成员只有p_str。
MySting();//无参数构造函数
MyString(char *pData);//带参数的构造函数
const char& operator[](unsigned int len)const;//重载[]
char &operator[](unsigned int len);//重载[]
MyString& operator=(const MyString &rhs);//重载=
int compare(const MyString &rhs)const;//比较运算
~MyString();//析构函数
friend ostream& operator<<(ostream & os,MyString &rhs);
自己定义的MyString类,为了简化把声明和定义都放在一个文件中。
class MyString
{
public:

	//无参数构造函数
	MyString()
	{
		p_str = new char[1];
		p_str[0] = '\0';
	}

	//带参数构造函数
	MyString(char *pData)
	{
		if(pData == NULL)
		{
			MyString();
		}
		else
		{
			int len = strlen(pData);
			p_str = new char[len + 1];
			for(int i = 0; i < len; ++i)
				p_str[i] = pData[i];
			p_str[len] = '\0';
		}
	}

	//重载[]接受const常量
	const char& operator[](unsigned int len) const
	{
		if(len > strlen(p_str))
		{
			len = strlen(p_str);
		}
		return p_str[len];
	}
	
	//重载[]优先接受非const变量
	char & operator=(unsigned int len)
	{
		if(len > strlen(p_str))
		{
			len = strlen(p_str);
		}
		return p_str[len];
	}

	//赋值构造函数
	MyString(const MyString &other)
	{
		int len = strlen(other.p_str);
		p_str = new char[len + 1];
		for(int i = 0; i < len; ++i)
			p_str[i] = other.p_str[i];
		p_str[len] = '\0'; 
	}
	
	//赋值运算符重载
	//MyString& operator=(const MyString &rhs)
	//{
	//	int len = strlen(rhs.p_str);
	//	char *tmp = new char[len + 1];
	//	for(int i = 0; i < len; ++i)
	//		tmp[i] = rhs.p_str[i];
	//	tmp[len] = '\0';
	//	delete p_str;
	//	p_str = tmp;
	//	return *this;
	//}

	//使用copy and swap技术实现赋值运算符
	MyString& operator=(const MyString &rhs)
	{
		if(this != &rhs)
		{
			MyString tmp(rhs);
			char *tp = tmp.p_str;
			tmp.p_str = p_str;
			p_str = tp;
		}
		return *this;
	}
	
	//比较操作
	int compare(const MyString &rhs) const
	{
		return strcmp(p_str,rhs.p_str);
	}

	//析构函数
	~MyString()
	{
		delete p_str;
	}
	//友源函数操作符<<
	friend ostream& operator<<(ostream &os,MyString &rhs);

private:
	char *p_str;
};

ostream& operator<<(ostream &os,MyString &rhs)
{
	return os<<rhs.p_str;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值