string实现

//实现string类
class SwyString
{
public:
	SwyString(const char* str = NULL)
	{
		//构造函数
		if (!str)
		{
			length = 0;
			data = new char[1];
			*data = '\0';
		}
		else
		{
			length = strlen(str);
			data = new char[length + 1];//strlen不计算\0
			strcpy(data, str);
		}
	};
	SwyString(const SwyString& str)
	{
		//拷贝构造函数 深拷贝 深复制
		length = str.size();
		data = new char[length + 1];
		strcpy(data, str.c_str());
	};
	~SwyString() 
	{
		delete []data;
		length = 0;
	};

	SwyString operator+(const SwyString& str) const
	{
		//重载 + 运算符
		SwyString temp;
		temp.length = length + str.size();
		temp.data = new char[temp.length + 1];
		strcpy(temp.data, data);
		strcat(temp.data, str.c_str());

		return temp;
	};
	SwyString& operator=(const SwyString& str)
	{
		//重载赋值运算符
		if (this == &str)
			return *this;
		delete[] data;
		length = str.size();
		data = new char[length + 1];
		strcpy(data, str.c_str());
		return *this;
	};
	SwyString operator+=(const SwyString& str)
	{
		//重载运算符+=
		length += str.length;
		char* newData = new char[length + 1];
		strcpy(newData, data);
		strcat(newData, str.c_str());
		delete[]data;
		data = newData;
		return *this;

	}
	inline bool operator==(const SwyString& str) const
	{
		//重载运算符 ==
		if (length != str.size())
			return false;
		return strcmp(data, str.c_str()) ? false : true;
	};
	char& operator[](int n) const 
	{
		//重载运算符 []
		if (n >= length)
			return data[length - 1];
		return data[n];
	};
	inline size_t size() const
	{
		return length;
	};
	inline const char* c_str() const
	{
		return data;
	};

	//两个友元函数 不属于此类,提供外界方便访问的接口
	friend istream& operator >> (istream& is, SwyString& str)
	{
		//重载 >> 操作符
		char temp[1000];//栈 临时空间
		is >> temp;
		str.length = strlen(temp);//字符串的长度 直到第一个'\0'为止
		str.data = new char[str.length + 1];//堆内存,除非delete 不会回收
		strcpy(str.data, temp);		//也是copy到'\0'为止 就退出
		return is;
	};
	friend ostream& operator << (ostream& os, SwyString& str)
	{
		//重载 << 操作符
		os << str.c_str();
		return os;
	};

private:
	char* data;	//字符串
	size_t length;	//长度
};
SwyString s;
	std::cin >> s;
	std::cout << s << ":" << s.size() << std::endl;

	char a[] = "hello";
	char b[] = "world";
	SwyString s1(a);
	SwyString s2(b);

	cout << s1 << "," << s2 << std::endl;
	cout << s1 + s2 << std::endl;

	SwyString s3 = s1 + s2;
	if (s1 == s3)
		std::cout << "equal\n";
	else
		std::cout << "not equal\n";
	s1 += s2;
	if (s1 == s3)
		std::cout << "equal\n";
	else
		std::cout << "not equal\n";



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值