编码实现字符串类CNString并进行字符串重载

编码实现字符串类CNString,该类有默认构造函数、类的拷贝函数、类的析构函数及运算符重载,需实现以下“=”运算符、“+”运算、“[]”运算符、“<”运算符及“>”运算符及“==”运算符(备注:可以用strcpy_s, strcat_s,但禁用STL及String类)

#ifndef CNString_H
#define CNString_H
#include<iostream>
#include <string.h>
class CNString
{
public:
	CNString();
	CNString(char *str);
	~CNString();
	CNString operator = (const CNString &obj);
	CNString operator + (const CNString &obj);
	char operator [] (int n);
	bool operator<(const CNString &obj);
	bool operator>(const CNString &obj);
	bool operator==(const CNString &obj);
private:
	int lens;
	char *str;
};

CNString::CNString()
{
	lens = 0;
	str = (char *)malloc(sizeof(char));
}

CNString::~CNString()
{
//	delete [] str;
	lens = 0;
}

CNString::CNString(char *enmu)//复制构造函数
{
	lens = 0;
	str =(char *) malloc(sizeof(char));
	while (enmu[lens] !='\0')
	{
		str[lens] = enmu[lens];
		lens++;
	}
	str[lens] = '\0';
}

CNString CNString::operator = (const CNString &obj)//赋值运算符重载
{
	
	this->lens = obj.lens;
	this->str = (char *)malloc(obj.lens*sizeof(char));//申请空间
	strcpy_s(this->str, obj.lens + 1, obj.str);//复制函数,第二个参数为源字符串长度
	return *this;
}

CNString CNString::operator + (const CNString &obj)//加号重载
{
	CNString Ans;
	Ans.lens = this->lens + obj.lens;
	Ans.str = (char *)malloc(20*sizeof(char));
	strcpy_s(Ans.str, this->lens + 1, this->str);
	strcat_s(Ans.str, Ans.lens + 1, obj.str);//第二个参数为粘贴后的长度
	*this = Ans;
	return *this;
}

char  CNString::operator [](int n)//[]重载
{
	char eum;
	eum = this->str[n];
	return eum;
}

bool CNString::operator < (const CNString &obj)
{
	bool res = 0;
	int len;
	if (this->lens <= obj.lens)
		len = this->lens;
	else
		len = obj.lens;
	for (int i = 0; i < len; i++)
	{
		if (this->str[i] < obj.str[i])
		{
			res = 1; break;
		}
		else if (this->str[i]> obj.str[i])
			break;
	}
	return res;
}

bool CNString::operator > (const CNString &obj)
{
	bool res = 0;
	int len;
	if (this->lens <= obj.lens)
		len = this->lens;
	else
		len = obj.lens;
	for (int i = 0; i < len; i++)
	{
		if (this->str[i] <obj.str[i])
			 break;
		else if ((this->str[i] >obj.str[i]))
		{
			res = 1; break;
		}
	
	}
	return res;
}

bool CNString::operator ==(const CNString &obj)
{
	bool res = 0;
	if (this->lens == obj.lens)
	{
		int i;
		for ( i = 0; i < lens; i++)
		{
			if (this->str[i] > obj.str[i] || this->str[i] < obj.str[i])
				 break;
		}
		if (i == lens)
			res = 1;
	}
	
	return res;
}
#endif

猜你喜欢

转载自blog.csdn.net/weixin_36387319/article/details/81298600