String__2018.06.13

本文介绍了一个使用C++实现的自定义字符串类,该类采用了引用计数技术来提高效率。文章详细展示了类的设计,包括构造函数、赋值运算符重载、比较运算符重载等,并提供了一个字符串连接的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码

#include <iostream>
#include <string>
#include <vld.h>

using namespace std;

class String
{
public:
	String(char *ptr = NULL)
	{
		if (ptr != NULL)
		{
			mpstr = new char[strlen(ptr) + 1 + 4];
			strcpy(mpstr + 4, ptr);
		}
		else
		{
			mpstr = new char[1 + 4];
			mpstr[4] = '\0';
		}
		*((int*)mpstr) = 1;
	}
	String(const String &str)
	{
		mpstr = str.mpstr;
		++(*(int *)mpstr);
	}
	String&operator=(const String &src)
	{
		if (this == &src)
		{
			return *this;
		}
		(*(int *)mpstr)--;
		if (*((int *)mpstr) == 0)
		{
			delete[]mpstr;
			mpstr = NULL;
		}
		mpstr = src.mpstr;
		++(*((int *)mpstr));
		return *this;
	}
	~String()
	{
		(*((int *)mpstr))--;
		if (*((int *)mpstr) == 0)
		{
			delete[]mpstr;
			mpstr = NULL;
		}
	}
	bool operator>(const String &src)
	{
		return strcmp(mpstr, src.mpstr) > 0;
	}
	bool operator<(const String &src)
	{
		return strcmp(mpstr, src.mpstr) < 0;
	}
	bool operator==(const String &src)
	{
		return strcmp(mpstr, src.mpstr) == 0;
	}
	int length()const { return strlen(mpstr+4); }
	char& operator[](int index)
	{
		char *tmp = new char[strlen(mpstr + 4) + 1 + 4];
		strcpy(tmp + 4, mpstr + 4);
		*((int*)tmp) = 1;
		--(*((int*)mpstr));
		mpstr = tmp;
		return (mpstr + 4)[index];
	}

private:
	char *mpstr;
	friend ostream& operator<<(ostream &out, const String &src);
	friend String operator+(const String &lhs, const String &rhs);

};

String operator+(const String &lhs, const String &rhs)
{
	int n = lhs.length() + rhs.length() + 1;
	cout << "lhs.mpstr为:" << lhs.mpstr+4 << endl;
	cout << "rhs.mpstr为:" << rhs.mpstr+4 << endl;

	char *ptmp = new char[n];
	cout << "lhs.length()的大小为:" << lhs.length() << endl;
	cout << "rhs.length()的大小为:" << rhs.length() << endl;

	cout << "ptmp数组开辟的大小为:" << n<<endl;
	char *q = "wangpeng";
	cout << "q的大小为:" << strlen(q) << endl;
	cout << "q为:" << q << endl;

	char *lhsT = (char *)(((int *)lhs.mpstr)+1);
	char *rhsT = (char *)(((int *)rhs.mpstr) + 1);

	strcpy(ptmp, lhsT);
	strcat(ptmp, rhsT);
	String tmp(ptmp);
	delete []ptmp;
	return tmp;
}

ostream& operator<<(ostream &out, const String &src)
{
	out << src.mpstr + 4;
	return out;
}
int main()
{
	String str1("wangpeng") ;
	String str2("hello");
	String str3 = str1 + str2;
	cout << str1 << endl;
	cout << str2 << endl;

	cout << str3 << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值