在my_string的基础上,将能重载的运算符全部重载掉
关系运算符:>、<、==、>=、<=、!=
加号运算符:+
取成员运算符:[]
赋值运算符: =
#include <iostream>
#include <string.h>
using namespace std;
class my_string
{
private:
char* str;
int len;
public:
void show()
{
cout<<this->str<<endl;
}
//无参构造
my_string()
{
this->str = new char[1]{'\0'};
this->len = 0;
}
//有参构造
my_string(char* str)
{
this->len = strlen(str);
this->str = new char[(this->len)+1];
strcpy(this->str,str);
}
//拷贝构造
my_string(const my_string& O)
{
this->len = O.len;
this->str = new char[O.len]{*(O.str)};
}
//bool my_empty() 判空
bool my_empty()
{
return this->len==0?true:false;
}
//int my_size() 求长度
int my_size()
{
return this->len;
}
//char *my_str() 转化为c风格字符串
char *my_str()
{
return this->str;
}
//关系运算符:>、<、==、>=、<=、!=
bool operator>(const my_string& O)const
{
if(strcmp(this->str,O.str) > 0)
return true;
else
return false;
}
bool operator<(const my_string& O)const
{
if(strcmp(this->str,O.str) < 0)
return true;
else
return false;
}
bool operator==(const my_string& O)const
{
if(strcmp(this->str,O.str) == 0)
return true;
else
return false;
}
bool operator>=(const my_string& O)const
{
if(strcmp(this->str,O.str) >= 0)
return true;
else
return false;
}
bool operator<=(const my_string& O)const
{
if(strcmp(this->str,O.str) <= 0)
return true;
else
return false;
}
bool operator!=(const my_string& O)const
{
if(strcmp(this->str,O.str) != 0)
return true;
else
return false;
}
//加号运算符:+
my_string operator+(const my_string& O)const
{
my_string temp;
strcpy(temp.str,this->str);
strcat(temp.str,O.str);
temp.len = this->len+O.len;
return temp;
}
//取成员运算符:[]
char operator[](int i)const
{
return this->str[i];
}
//拷贝赋值,赋值运算符: =
my_string& operator=(const my_string& R)
{
if(this!=&R)
{
this->len = R.len;
// delete this->str;
this->str = new char[R.len+1];
strcpy(this->str,R.str);
}
return *this;
}
};
int main()
{
my_string s0;
cout<<"s0 size="<<s0.my_size()<<endl;
my_string s1("abcdefg");
cout<<"s1 size="<<s1.my_size()<<endl;
my_string s2 = s1;
cout<<"s2 size="<<s2.my_size()<<endl;
my_string s3;
s3 = s1;
cout<<"s3 size="<<s3.my_size()<<endl;
my_string s4 = "abc";
cout<<"s4 size="<<s4.my_size()<<endl;
s4 = "45678";
cout<<"s4 size="<<s4.my_size()<<endl;
//关系运算符:>、<、==、>=、<=、!=
my_string s5 = "abd";
cout<<(s5>s4?"YES":"NO")<<endl;
cout<<(s5<s4?"YES":"NO")<<endl;
cout<<(s5==s4?"YES":"NO")<<endl;
cout<<(s5>=s4?"YES":"NO")<<endl;
cout<<(s5<=s4?"YES":"NO")<<endl;
cout<<(s5!=s4?"YES":"NO")<<endl;
//加号运算符:+
my_string s6 = s1+s5;
s6.show();
cout<<s6[0]<<"\t"<<s6[2]<<endl;
s5 = s6;
s5.show();
my_string s7 = s6;
s7.show();
char* p = s1.my_str();
cout<<p<<endl;
cout << "Hello World!" << endl;
return 0;
}