在my_string的基础上,将能重载的运算符全部重载掉
关系运算符:>、=、
加号运算符:+
取成员运算符:[]
赋值运算符: =
#include <iostream>
#include<string>
#include<string.h>
using namespace std;
class my_string
{
private:
char*str;
int len;
public:
~my_string()
{
delete(str);
}
my_string(){}
my_string(char *p)
{
str = new char;
str = p;
}
bool my_empty();
int my_size();
char *my_str();
my_string &operator=(const my_string&p)
{
this->str= p.str;
return *this;
}
friend bool operator>(my_string&,my_string&);
friend bool operator<(my_string&,my_string&);
friend bool operator==(my_string&,my_string&);
friend bool operator>=(my_string&,my_string&);
friend bool operator<=(my_string&,my_string&);
friend bool operator!=(my_string&,my_string&);
friend my_string operator+(my_string&,my_string&);
char operator[](int i)
{
return *(this->str+i);
}
};
my_string operator+(my_string&p,my_string&q)
{
my_string temp;
strcpy(temp.str,p.str);
strcat(temp.str,q.str);
return temp;
}
bool operator>=(my_string&p,my_string&q)
{
if(strcmp(p.my_str (),q.my_str ())>=0)
return true;
else
return false;
}
bool operator<=(my_string&p,my_string&q)
{
if(strcmp(p.my_str (),q.my_str ())<=0)
return true;
else
return false;
}
bool operator!=(my_string&p,my_string&q)
{
if(strcmp(p.my_str (),q.my_str ())!=0)
return true;
else
return false;
}
bool operator==(my_string&p,my_string&q)
{
if(strcmp(p.my_str (),q.my_str ())==0)
return true;
else
return false;
}
bool operator>(my_string&p,my_string&q)
{
char*p1 = p.my_str ();
char*p2 = q.my_str ();
if(strcmp(p1,p2)>0)
return true;
else
return false;
}
bool operator<(my_string&p,my_string&q)
{
if(strcmp(p.str,q.str)<0)
return true;
else
return false;
}
bool my_string::my_empty()
{
if(*str)
return false;
else
return true;
}
int my_string::my_size()
{
len=0;
char *p=str;
while(*p)
{
len++;
p++;
}
return len;
}
char *my_string::my_str()
{
return str;
}
int main()
{
my_string s1("hqyj"),s2("abcdefghijkl");
cout<<"is empty?"<<s1.my_empty ()<<endl;
cout<<"size>>>"<<s1.my_size ()<<endl;
cout<<"s1 str>>>"<<s1.my_str ()<<endl;
s2=s1;
cout<<"s2 str>>>"<<s2.my_str ()<<endl;
my_string s3;
s3=s1;
cout<<"s3 str>>>"<<s3.my_str ()<<endl;
my_string aa=("abcdefghijklmnopq");
cout<<aa.my_str ()<<endl;
cout<<aa.my_size ()<<endl;
cout<<aa.my_empty ()<<endl;
my_string c1("abcd"),c2("qwer");
cout<<c1.my_str ()<<endl;
cout<<c2.my_str ()<<endl;
cout<<(c1>=c2?"c1>=c2":"c1<=c2")<<endl;
my_string c3;
c3 = (c1+c2);
cout<<c3.my_str ()<<endl;
cout<<c3[1]<<endl;
cout<<c3[2]<<endl;
cout<<c3[5]<<endl;
system("pause");
return 0;
}
结果演示: