代码
#include <iostream>
#include<cstring>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
my_string()
{
str=new char[128];
memset(str,0,128);
}
my_string(const char *s)
{
str=new char[128];
memset(str,0,128);
strcpy(str,s);
}
bool operator >(const my_string &R)
{
return strcmp(this->str,R.str)>0;
}
bool operator <(const my_string &R)
{
return strcmp(this->str,R.str)<0;
}
bool operator ==(const my_string &R)
{
return strcmp(this->str,R.str)!=0;
}
my_string operator +(const my_string &R)
{
my_string temp;
temp.str=new char[strlen(this->str)+strlen(R.str)];
strcpy(temp.str,this->str);
strcat(temp.str,R.str);
return temp;
}
my_string &operator +=(const my_string &R)
{
char *temp=new char[strlen(this->str)];
strcpy(temp,this->str);
delete this->str;
this->str=new char[strlen(this->str)+strlen(R.str)];
strcpy(this->str,temp);
strcat(this->str,R.str);
delete[] temp;
return *this;
}
char& operator[](int index)
{
return this->str[index];
}
char *show()
{
return str;
}
};
int main()
{
my_string s1("hello");
my_string s2("world");
my_string s3;
cout<<(s1>s2?"yes":"no")<<endl;
cout<<(s2>s1?"yes":"no")<<endl;
cout<<(s1+s2>s2?"yes":"no")<<endl;
cout<<(s1==s1?"yes":"no")<<endl;
s1+="123";
cout<<s1.show()<<endl;
s1[6]='q';
cout<<s1.show()<<endl;
s3=s1+s2;
cout<<s3.show()<<endl;
return 0;
}
验证: