String类的部分实现

#include<string.h>
#include<iostream>
#include<Windows.h>
using namespace std;
class String
{
	char *str1;
public:
	String()
	{
	}
	String (const char *s)
	{
		str1 = new char[strlen(s) + 1];
		strcpy(str1, s);
	}
	String(const String &y)
	{
		str1 = new char[strlen(y.str1) + 1];
		strcpy(str1, y.str1);
	}
	~String()
	{
		delete []str1;
		str1=NULL;
	}
	String& operator = (const String &y)
	{
		if(strcmp(str1,y.str1)==0)
		return *this;
		delete[]str1;
		str1 = new char[strlen(y.str1) + 1];
		strcpy(str1, y.str1);
		return *this;
	}
	
	String operator +(String &y)
	{
		String temp;
		temp.str1 = new char[strlen(str1) + strlen(y.str1) + 1];
		strcat(temp.str1,str1);
		strcat(temp.str1, y.str1);
		return temp;
	}
	friend ostream& operator<<(ostream &out,const String &y);
	friend istream& operator>>(istream &in,const String &y);
	char operator[](size_t i)
	{
		return str1[i];
	}
};
ostream& operator<<(ostream &out,const String &y)
	{
		out<<y.str1;
		return out;
	}
istream& operator>>(istream &in,const String& y)
{
	
	in>>y.str1;
	return in;
}

int main()
{
	String st1("world");
	String st2("hello");
	String st3;
	st3=st2+st1;
	//cin>>st1;
	
	cout<<st3<<endl;
	cout<<st2[2]<<endl;
	cout << st1 << endl;
	cout << st2 << endl;
	//return 0;
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值