Mystring的实现(实现C++提供的string类)

注意运算符的重载即可:

class My_String
{
private:
	char* str;
public:
	My_String()
	{
		str = nullptr;
	}
	My_String(const char* src)
	{
		if(src!=nullptr)
		{ 
			int len = strlen(src) + 1;
			str = new char[len];
			memmove(str, src, sizeof(char) * len);
		}
		
	}
	My_String(const My_String& src)
	{
		int len = strlen(src.str) + 1;
		str = new char[len];
		memmove(str, src.str, sizeof(char) * len);
	}
	~My_String()
	{
		delete[]str;
		str = nullptr;
	}
	void print()const
	{
		cout << str << endl;
	}
	My_String& operator=(const My_String& cp)
	{
		if (this != &cp)
		{
			delete[]this->str;
			int len = strlen(cp.str) + 1;
			str = new char[len];
			memmove(str, cp.str, sizeof(char) * len);
		}
		return*this;
	}
	My_String operator+(const My_String& cp)const 
	{
		My_String tmp;
		int len = strlen(this->str) + strlen(cp.str) + 1;
		tmp.str = new char[len];
		strcpy_s(tmp.str, len, this->str);
		strcat_s(tmp.str, len, cp.str);
		return tmp;
	}
	My_String& operator+=(const My_String& cp)
	{
		My_String tmp;
		int len = strlen(this->str) + strlen(cp.str) + 1;
		tmp.str = new char[len];
		strcpy_s(tmp.str, len, this->str);
		strcat_s(tmp.str, len, cp.str);
		delete[]this->str;
		this->str = tmp.str;
		tmp.str = nullptr;
		return*this;
	}
	My_String operator+(const char* cp)const
	{
		My_String tmp;
		int len = strlen(this->str) + strlen(cp) + 1;
		tmp.str = new char[len];
		strcpy_s(tmp.str, len, this->str);
		strcat_s(tmp.str, len, cp);
		return tmp;
	}
	char& operator[](const int n)
	{
		assert(this!=nullptr&&n >= 0&&n <= (strlen(this->str)));
		return this->str[n];
	}
	int Sz()const 
	{
		return strlen(this->str);
	}
	char*& Get()
	{
		return this->str;
	}
	friend My_String operator+(const char* cpy, My_String& cp);
};
My_String operator+(const char * cpy,My_String& cp)
{
	My_String tmp;
	int len = strlen(cpy) + strlen(cp.str )+ 1;
	tmp.str = new char[len];
	strcpy_s(tmp.str, len, cpy);
	strcat_s(tmp.str, len, cp.str);
	return tmp;
}
int main()
{
	My_String s1{ "guorui" };
	My_String s2{ "xiaomao" };
	My_String s3;
	s3 = s1;
	s3.print();
	s3 = s1 + s2;
	s3.print();
	s3 = s1 += s2;
	s3.print();
	s3 = s1 + "and";
	s3.print();
	s3 = "xy" + s2;
	s3.print();
	char ch = s2[2];
	cout << ch <<endl;
	return 0;
}

需要注意的只有,字符串+对象   这个+的重载与对象+对象与对象+字符串都互不相同,字符串+对象需要用到友元函数。(不然就十分麻烦)
可以看到,我只进行了+,=以及[]的重载。还有许多C++中string类提供的方法与运算符重载我并没有实现,只是实现了几个比较关键的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

g162512

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值