在昨天my_string的基础上,将能重载的运算符全部重载掉
关系运算符:>、<、==、>=、<=、!=
加号运算符:+
取成员运算符:[]
赋值运算符: =
#include <iostream>
#include <cstring>
using namespace std;
class my_string
{
private:
char*str;
int len;
public:
my_string(){} //无参构造
my_string(char *str) //有参构造
{
this->str=new char[128];
strcpy(this->str,str);
len=strlen(str);
}
my_string(const my_string&other):str(other.str),len(other.len){}
my_string&operator =(const my_string&other)
{
if(this!=&other)
{
if(this->str!=NULL)
{
delete this->str;
this->str=NULL;
}
this->str=new char[128];
strcpy(str,other.str);
this->len=other.len;
}
return *this;
}
~my_string()
{
delete str;
}
void display()
{
cout<<str<<"\t"<<len<<endl;
}
bool my_empty()
{
return strlen(str)==0?true:false;
}
int my_size()
{
return strlen(str);
}
char *my_str()
{
return str;
}
//>
bool operator >(my_string &R)
{
if(strcmp(this->str,R.str)>0)
{
return 1;
}
return 0;
}
//<
bool operator <( my_string &R)
{
if(strcmp(this->str,R.str)<0)
{
return true;
}
return false;
}
//==
bool operator ==( my_string &R)
{
if(strcmp(this->str,R.str)==0)
{
return 1;
}
return 0;
}
//<=
bool operator <=( my_string &R)
{
if(strcmp(this->str,R.str)>0)
{
return 1;
}
return 0;
}
//!=
bool operator !=( my_string &R)
{
if(strcmp(this->str,R.str)>0)
{
return 1;
}
return 0;
}
//+
const my_string operator +(const my_string &R)
{
strcat(this->str,R.str);
return *this;
}
//[]
char operator [](int i)
{
return this->str[i];
}
};
int main()
{
my_string str1;
char* str="hqyj";
my_string str2(str);
cout<<"str2"<<endl;
cout<<str2.my_empty()<<endl;
str2.display();
my_string str3(str2);
cout<<"str3"<<endl;
cout<<str3.my_empty()<<endl;
str3.display();
str1=str3;
cout<<"str1"<<endl;
cout<<str1.my_empty()<<endl;
str1.display();
my_string str4("hello");
my_string str5("world");
cout<<"str4>str5:"<<(str4>str5)<<endl;
cout<<"str4<str5:"<<(str4<str5)<<endl;
cout<<"str4==str5:"<<(str4>str5)<<endl;
cout<<"str4<=str5:"<<(str4>str5)<<endl;
cout<<"str4!=str5:"<<(str4>str5)<<endl;
my_string str6=str4+str5;
cout<<"str4+str5="<<str6.my_str()<<endl;
cout<<"str4[3]="<<str4[3]<<endl;
return 0;
}