在myString基础上,将=,+,==,<=,>=,<,>,!=,<<,>>运算符全部进行重载
代码
#include <iostream>
#include <cstring>
using namespace std;
class myString
{
private:
char *str;
int size;
public:
myString():size(10)
{
str = new char[size];
strcpy(str,"");
}
myString(const char *s)
{
size = strlen(s);
str = new char [size+1];
strcpy(str,s);
}
myString(const myString &other):size(other.size)
{
str=new char[size+1];
strcpy(str,other.str);
}
~myString()
{
delete []str;
}
bool empty()
{
return size==0;
}
int length()
{
return size;
}
const char * c_str()
{
return str;
}
char &at(int pos)
{
char &m = str[pos];
return m;
}
char &operator[](int pos)
{
return str[pos];
}
myString &operator=(const myString &R)
{
strcpy(this->str,R.str);
this->size = R.size;
return *this;
}
const myString operator+(const myString &R)const
{
myString temp;
temp.str = strcat(this->str,R.str);
temp.size = this->size + R.size;
return temp;
}
bool operator==(const myString &R)const
{
return strcmp(this->str,R.str)==0 && this->size==R.size;
}
bool operator!=(const myString &R)const
{
return strcmp(this->str,R.str) && this->size!=R.size;
}
bool operator>(const myString &R)const
{
return strcmp(this->str,R.str)>0 && this->size>R.size;
}
bool operator<(const myString &R)const
{
return strcmp(this->str,R.str)<0 && this->size<R.size;
}
bool operator<=(const myString &R)const
{
return strcmp(this->str,R.str)<=0 && this->size<=R.size;
}
bool operator>=(const myString &R)const
{
return strcmp(this->str,R.str)>=0 && this->size>=R.size;
}
friend ostream &operator<<(ostream &L,const myString &R);
friend istream &operator>>(istream &L,const myString &R);
};
ostream &operator<<(ostream &L,const myString &R)
{
L<<R.str<<endl;
return L;
}
istream &operator>>(istream &L,const myString &R)
{
L>>R.str;
return L;
}
int main()
{
myString s1("hello");
myString s2(s1);
cout<<"s2 = "<<s2.c_str()<<endl;
myString s3;
s3 = s2;
cout<<"s3 = "<<s3.c_str()<<endl;
s3[2] = 'D';
cout<<"s3 = "<<s3.c_str()<<endl;
s2 = (s1 + s3);
cout<<"s2 = "<<s2.c_str()<<endl;
myString s4(s3);
cout<<"s4 = "<<s4.c_str()<<endl;
cout<<"s3 = "<<s3.c_str()<<endl;
if(s4 == s3){
cout<<"yes"<<endl;
}else{
cout<<"no"<<endl;
}
cout<<s2;
cout<<"s1 = "<<s1.c_str()<<endl;
cin>>s1;
cout<<"s1 = "<<s1.c_str()<<endl;
return 0;
}
运行结果