#include <iostream>
#include <cstring>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
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 l,my_string r);
//加法运算符重载
// const my_string operator +(const my_string r)const
// {
// my_string temp;
// temp.len=this->len+r.len;
// temp.str=strcat(this->str,r.str);
// return temp;
// }
//大于号
bool operator >(const my_string& r)
{
if(strcmp(this->str,r.str)>0)
return true;
else
return false;
}
//小于号
bool operator <(const my_string& r)
{
if(strcmp(this->str,r.str)<0)
return true;
else
return false;
}
//等于号
bool operator ==(const my_string& r)
{
if(strcmp(this->str,r.str)==0)
return true;
else
return false;
}
//取成员运算符
char operator [](int i)
{
return (this->str)[i];
}
//无参构造
my_string(){};
//有参构造
my_string(char s,int l)
{
str=new char[l+1];
for(int i=0;i<l;i++)
{
str[i]=s;
}
str[l]=0;
len=l;
}
my_string(char *s)
{
len=strlen(s);
str=new char[len+1];
strcpy(str,s);
str[len]=0;
}
//拷贝构造
my_string(const my_string &o)
{
len=o.len;
str=new char[o.len+1];
for(int i=0;i<o.len+1;i++)
{
*(str+i)=*(o.str+i);
}
*(o.str+len)=0;
}
//拷贝赋值
my_string& operator=(const my_string &r)
{
//防止给自己赋值
if(&r!=this)
{
len=r.len;
if(str!=NULL) //防止内存泄露
{
delete str;
str=NULL;
}
str=new char[r.len+1]; //深拷贝
for(int i=0;i<r.len+1;i++)
{
*(str+i)=*(r.str+i);
}
*(str+len+1)=0;
}
return *this;
}
void show()
{
cout<<"len="<<len<<" str="<<str<<endl;
}
bool my_empty()
{
if(*str==0)
return true;
else
return false;
}
int my_size()
{
return len;
}
//转化为c风格字符串
char *my_str()
{
return str;
}
};
bool operator >=(my_string& l,my_string& r)
{
if(strcmp(l.str,r.str)>=0)
return true;
else
return false;
}
bool operator <=(my_string& l,my_string& r)
{
if(strcmp(l.str,r.str)<=0)
return true;
else
return false;
}
bool operator !=(my_string& l,my_string& r)
{
if(strcmp(l.str,r.str)!=0)
return true;
else
return false;
}
my_string operator +(my_string l,my_string r)
{
my_string temp;
temp.len=l.len+r.len;
temp.str=strcat(l.str,r.str);
return temp;
}
int main()
{
my_string s1('h',4);
my_string s2("string");
my_string s3=s2;
s1.show();
s2.show();
s3.show();
s3=s1;
s3.show();
my_string s4=s2+s1;
s4.show();
s3>s4? cout<<"yes"<<endl:cout<<"no"<<endl;
s3>=s4? cout<<"yes"<<endl:cout<<"no"<<endl;
s3<s4? cout<<"yes"<<endl:cout<<"no"<<endl;
s3<=s4? cout<<"yes"<<endl:cout<<"no"<<endl;
s3==s4? cout<<"yes"<<endl:cout<<"no"<<endl;
s3!=s4? cout<<"yes"<<endl:cout<<"no"<<endl;
cout<<s4[3]<<endl;
cout<<s3.my_empty()<<endl;
cout<<s2.my_size()<<endl;
cout<<s1.my_size()<<endl;
cout << "Hello World!" << endl;
return 0;
}
在昨天my_string的基础上,将能重载的运算符全部重载掉
最新推荐文章于 2024-07-24 14:05:37 发布