String类实现

#include <iostream>
#include <cstring>
#include <assert.h>
using namespace std;

class String
{
public:
	String()
	{
		char *m_pstr = new char[1];
		m_pstr[0] = '\0';
	}

	String(const char *pstr)
	{
		assert(pstr != NULL);
		m_pstr = new char[strlen(pstr) + 1];
		strcpy(m_pstr, pstr);
	}

	String(const String & rhs)
	{
		m_pstr = new char[strlen(rhs.m_pstr) + 1];
		strcpy(m_pstr, rhs.m_pstr);
	}

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

	String & operator=(const String  & rhs)
	{
		if (this != &rhs)
		{
			delete[] m_pstr;
			m_pstr = new char[strlen(rhs.m_pstr) + 1];
			strcpy(m_pstr, rhs.m_pstr);
		}
		return *this;
	}

	String operator+(const String &rhs) const
	{
		String newString;
		if (!rhs.m_pstr)
			newString = *this;
		else if (!m_pstr)
			newString = rhs;
		else
		{
			newString.m_pstr = new char[strlen(m_pstr) + strlen(rhs.m_pstr) + 1];
			strcpy(newString.m_pstr, m_pstr);
			strcat(newString.m_pstr, rhs.m_pstr);
		}
		return newString;
	}

	char operator [](const unsigned int index)
	{
		if (index >= 0 && index<strlen(m_pstr))
			return m_pstr[index];
		else
		{
			cout << "Error: the index of [] is invalid." << endl;
			exit(0);
		}
	}

	friend ostream& operator<<(ostream & output, const String &rhs) 
	{
		output << rhs.m_pstr;
		return output;
	}

	friend istream& operator>>(istream& is, String& rhs)
	{
		char temp[255];
		is >> temp;
		rhs = temp;
		return is;
	}

	bool operator==(const String& rhs)
	{
		if (strlen(m_pstr) != strlen(rhs.m_pstr))
			return false;
		else
			return strcmp(m_pstr,rhs.m_pstr) ? false : true;
	}

	size_t size() const
	{
		return strlen(m_pstr);
	}

	const char* c_str() const
	{
		return m_pstr;
	}

private:
	char *m_pstr;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值