String各类运算符重载的编写示例



class myString
{
public:
	myString& operator=(char* s);
	myString& operator=(const myString& s);
	char& operator[](int i);//重载[],实现数组运算
	const char& operator[](int i)const;
	myString& operator+=(const myString& s);
	myString& operator+=(const char* s);
	friend ostream& operator<<(ostream& out,myString& s);
	friend istream& operator>>(istream& in,myString& s);
	friend bool operator<(const myString& left,const myString& right);
	friend bool operator>(const myString& left,const myString& right);
	friend bool operator==(const myString& left,const myString& right);
	friend bool operator!=(const myString& left,const myString& right);
	char* getData();//获取data指针
	int length();
private:
	int size;
	char *data;
};

myString& myString::operator=(char* s)
{
	if (data!=NULL)
	{
		delete []data;
	}
	size = strlen(s);
	data = new char[size+1];
	strcpy(data,s);//复制目标字符串
	return *this;
}

myString& myString::operator =(const myString& s)
{
	if (this==&s)
	{
		return *this;
	}
	if (data != NULL)
	{
		delete []data;
	}
	size = strlen(s.data);
	data = new char[size+1];
	strcpy(data,s.data);
	return *this;
}

char& myString::operator[](int i)
{
	return data[i];
}

const char& myString::operator [](int i)const
{
	return data[i];
}

myString& myString::operator+=(const myString& s)//
{
	int len = size + s.size + 1;
	char *temp = data;
	data = new char[len];
	size = len - 1;
	strcpy(data,temp);
	strcat(data,s.data);
	delete []temp;
	return *this;
}

myString& myString::operator+=(const char* s)
{
	if (s==NULL)
	{
		return *this;
	}
	int len = size + strlen(s) + 1;
	char *temp = data;
	data = new char[len];
	size = len - 1;
	strcpy(data,temp);
	strcat(data,s);
	delete []temp;
	return *this;
}

int myString::length()
{
	return size;
}

ostream& operator<<(ostream &out,myString &s)
{
	for (int i = 0;i<s.length();i++)
	{
		out << s[i] << " ";
	}
	return out;
}

istream& operator>>(istream& in,myString& s)
{
	char p[50];
	in.getline(p,50);
	s = p;
	return in;
}

bool operator<(const myString& left,const myString& right)
{
	int i = 0;
	while (left[i]==right[i]&&left[i]!=0&&right[i]!=0)
	{
		i++;
	}
	return left[i]-right[i] < 0?true:false;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值