在my_string的基础上,将能重载的运算符全部重载掉
关系运算符:>、<、==、>=、<=、!=
加号运算符:+
取成员运算符:[]
赋值运算符: =
实现代码
#include <iostream>
#include <cstring>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
//无参构造
my_string()
{
str=NULL;
len=0;
}
//有参构造
my_string(char *str)
{
this->str=new char[128];
strcpy(this->str,str);
len=strlen(this->str);
}
//拷贝构造
my_string(const my_string &other)
{
this->str=new char[128];
strcpy(this->str,other.str);
this->len=other.len;
}
//拷贝赋值,=运算符重载
my_string& operator=(const my_string &other)
{
if(this->str != NULL)
{
delete this->str; //将原先内存释放,方式出现内存泄露
this->str = NULL;
}
this->str=new char[128];
strcpy(this->str,other.str);
this->len=other.len;
}
//判空
bool my_empty()
{
if(len==0)
{
return 1;
}
return 0;
}
//求长度
int my_size()
{
return len;
}
//转化为c风格字符串
char *my_str()
{
return str;
}
//>
bool operator>(const my_string &R ) const
{
if(strcmp(this->str,R.str)>0)
{
return 1;
}
return 0;
}
//<
bool operator<(const my_string &R ) const
{
if(strcmp(this->str,R.str)<0)
{
return 1;
}
return 0;
}
//==
bool operator==(const my_string &R ) const
{
if(strcmp(this->str,R.str)==0)
{
return 1;
}
return 0;
}
//>=
bool operator>=(const my_string &R ) const
{
if(strcmp(this->str,R.str)>=0)
{
return 1;
}
return 0;
}
//<=
bool operator<=(const my_string &R ) const
{
if(strcmp(this->str,R.str)<=0)
{
return 1;
}
return 0;
}
//!=
bool operator!=(const my_string &R ) const
{
if(strcmp(this->str,R.str)!=0)
{
return 1;
}
return 0;
}
//+
const my_string operator+( const my_string &R ) const
{
my_string str(*this);
strcat(str.str,R.str);
str.len+=R.len;
return str;
}
//[]
const char operator[](const int num)const
{
if(num>=0&&num<=len-1)
{
return *(this->str+num);
}
return '\0';
}
};
int main()
{
my_string str1("hello");
my_string str2("world");
cout<<boolalpha;
cout<<"str1:"<<str1.my_str()<<endl;
cout<<"str2:"<<str2.my_str()<<endl;
cout<<"str1>str2:"<<(str1>str2)<<endl;
cout<<"str1<str2:"<<(str1<str2)<<endl;
cout<<"str1==str2:"<<(str1==str2)<<endl;
cout<<"str1>=str2:"<<(str1>=str2)<<endl;
cout<<"str1<=str2:"<<(str1<=str2)<<endl;
cout<<"str1!=str2:"<<(str1!=str2)<<endl;
my_string str3=str1+str2;
cout<<"str1+str2="<<str3.my_str()<<endl;
cout<<"str1[0]="<<str1[0]<<endl;
cout<<"str2[4]="<<str2[4]<<endl;
return 0;
}
运行结果
![](https://i-blog.csdnimg.cn/blog_migrate/bf18614cbe72207baa5c1887c5a8e2a8.png)