string类

以前对字符串的操作都是char,但是在C++中使用string更加的方便,那么底层的实现是怎样的呢?接下来我来实现一下:

#include <iostream>

class String;
class Iterator
{
public:
	Iterator(String *ps,int ids):pstr(ps),index(ids){}

	bool operator!=(const Iterator rhs)
	{
		return index == rhs.index;
	}

	char& operator*();

	const Iterator operator++(int)
	{
		Iterator tmp(*this);
		index++;
		return tmp;
	}

	Iterator& operator++()
	{
		index++;
		return *this;
	}
private:
	String *pstr;
	int index;
};

#pragma warning(disable:4996);

class String
{
public:
	typedef Iterator iterator;
	String(char *ptr)
		:mptr(new char[strlen(ptr)+1]())
	{
		strcpy_s(mptr,strlen(ptr)+1,ptr);
	}

	//String str2 = str1 + "world";
	const String operator+(char* rhs)
	{
		char *tmp = new char[strlen(mptr) + strlen(rhs) + 1]();
		strcpy_s(tmp,strlen(mptr)+1,mptr);
		strcat(tmp,rhs);
		String str(tmp);
		delete[] tmp;
		return str;
	}

	//String str4 = str1 + str2;
	const String operator+(const String& rhs)
	{
		char *tmp = new char[strlen(mptr) + strlen(rhs.mptr) + 1]();
		strcpy_s(tmp,strlen(mptr)+1,mptr);
		strcat(tmp,rhs.mptr);
		String str(tmp);
		delete[] tmp;
		return str;
	}

	//深拷贝
	String(const String& rhs)
	{
		mptr = new char[strlen(rhs.mptr) + 1]();
		strcpy_s(mptr,strlen(rhs.mptr)+1,rhs.mptr);
	}


	bool operator<(const String& rhs)
	{
		return strcmp(mptr,rhs.mptr) < 0;
	}

	bool operator!=(const String& rhs)
	{
		return strcmp(mptr,rhs.mptr) != 0;
	}

	char& operator[](int index)
	{
		return mptr[index];
	}

	iterator begin()
	{
		return iterator(this,0);
	}

	iterator end()
	{
		return iterator(this,strlen(mptr));
	}

	~String()
	{
		delete[] mptr;
		mptr = NULL;
	}

private:
	char *mptr;
	friend const String operator+(char *,const String&);
	friend std::ostream& operator<<(std::ostream& ,const String& );
	friend std::istream& operator>>(std::istream& ,const String& );
};


//String str3 = "hi" + str1;对象做右操作数,在类外实现
const String operator+(char *lhs,const String& rhs)
{
	char *tmp = new char[strlen(lhs) + strlen(rhs.mptr) + 1]();
	strcpy_s(tmp,strlen(lhs)+1,lhs);
	strcat(tmp,rhs.mptr);
	String str(tmp);
	delete[] tmp;
	return str;
}

std::ostream& operator<<(std::ostream& out,const String& rhs)
{
	out << rhs.mptr;
	return out;
}

std::istream& operator>>(std::istream& in,const String& rhs)
{
	in >> rhs.mptr;
	return in;
}

char& Iterator::operator*()
{
	return (*pstr)[index];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值