在my_string的基础上,将能重载的运算符全部重载掉
关系运算符:>、<、==、>=、<=、!=
加号运算符:+
取成员运算符:[]
赋值运算符: =
上次my_string重载加了点内容
#include <iostream>
#include<string.h>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
//无参构造函数
my_string()
{
str=NULL;
}
//析构函数
~my_string()
{
delete []str;
str=NULL;
}
//有参构造函数
my_string(int l,char* s)
{
len = l;
str = new char[len];
for(int i=0;i<len;i++)
{
str[i]=s[i];
}
}
//拷贝构造函数
my_string(my_string& O)
{
this->len = O.len;
//strcpy(str,O.str);
for (int i = 0; i < this->len; i++)
{
this->str[i]=O.str[i];
}
}
//拷贝赋值
my_string& operator = (const my_string& R)
{
if(this != &R)
{
this->len = R.len;
//strcpy(str,R.str);
for (int i = 0; i < this->len; i++)
{
this->str[i]=R.str[i];
}
}
return *this;
}
//判空
bool my_empty()
{
if(len==0)
return true;
else
return false;
}
//求长度
int my_size()
{
//cout<<len<<endl;
return len;
}
//转化为c风格字符串
char* my_str()
{
return str;
}
void display()
{
cout<<*str<<endl;
}
//>
bool operator >(my_string &R)
{
int temp;
if(this->len>R.len)
temp=R.len;
else
temp=this->len;
for(int i=0;i<temp;i++)
{
if(this->str[i]>R.str[i])
return true;
}
return false;
}
//<
bool operator <(my_string &R)
{
int temp;
if(this->len>R.len)
temp=R.len;
else
temp=this->len;
for(int i=0;i<temp;i++)
{
if(this->str[i]<R.str[i])
return true;
}
return false;
}
//==
bool operator ==(my_string &R)
{
for(int i=0;i<len;i++)
{
if(str[i]!=R.str[i])
return false;
}
return true;
}
//>=
bool operator >=(my_string &R)
{
for(int i=0;i<len;i++)
{
if(str[i]>=R.str[i])
return true;
}
return false;
}
//<=
bool operator <=(my_string &R)
{
for(int i=0;i<len;i++)
{
if(str[i]<=R.str[i])
return true;
}
return false;
}
// !=
bool operator !=(my_string &R)
{
for(int i=0;i<len;i++)
{
if(str[i]==R.str[i])
return false;
}
return true;
}
//+
my_string operator +(my_string &R)
{
int i,j;
my_string temp;
temp.len=this->len+R.len;
for(i=0;i<this->len;i++)
{
temp.str[i]=this->str[i];
}
for(j=0;j<R.len;j++)
{
temp.str[i+j]=R.str[j];
}
return temp;
}
//[]
char& operator[](int i)
{
return str[i];
}
//=
my_string& operator=(my_string &R)
{
this->len = R.len;
this->str = new char[this->len];
for (int i = 0; i < this->len; i++)
{
this->str[i]=R.str[i];
}
return *this;
}
};
int main()
{
my_string s1(5,"hello");
cout<<s1.my_size()<<endl;
cout<<s1.my_str()<<endl;
cout<<(s1.my_empty()?"yes":"no")<<endl;
my_string s2;
s2 = s1;
cout<<s2.my_size()<<endl;
cout<<s2.my_str()<<endl;
my_string s3(2,"hf");
cout<<(s1>s3?"yes":"no")<<endl;
cout<<(s1<s3?"yes":"no")<<endl;
cout<<(s1>=s3?"yes":"no")<<endl;
cout<<(s1<=s3?"yes":"no")<<endl;
cout<<(s1!=s3?"yes":"no")<<endl;
cout<<(s1==s3?"yes":"no")<<endl;
cout<<(s1!=s2?"yes":"no")<<endl;
cout<<(s1==s2?"yes":"no")<<endl;
my_string s4;
s4=s1;
cout<<s4.my_str()<<endl;
cout<<s4[0]<<endl;
return 0;
}