封装my_string并实现=、+、==、!=、==、>、<、<<、>>等运算符的重载
#include <iostream>
#include<cstring>
using namespace std;
class my_string
{
private:
char *cstr;
int len;
public:
my_string():cstr(NULL),len(0) {/*cout<<"无参构造"<<endl;*/} //无参构造函数
my_string(const char *str) //有参构造函数
{
len=strlen(str);
cstr=new char[len+1];
strcpy(cstr,str);
//cout<<"有参构造"<<endl;
}
my_string(const my_string &other) //拷贝构造函数
{
this->len=other.len;
this->cstr=new char[len+1];
strcpy(this->cstr,other.cstr);
//cout<<"拷贝构造"<<endl;
}
~my_string() //析构函数
{
if(cstr!=NULL)
{
delete cstr;
}
cout<<"析构函数"<<endl;
}
//运算符重载
friend istream &operator>>(istream &L,my_string &R);// >>重载
friend ostream &operator<<(ostream &L,my_string &R);// <<重载
my_string &operator=(my_string &R) //运算符重载=
{
if(this->cstr!=NULL)
{
strcpy(this->cstr,R.cstr);
this->len=R.len;
}
else
{
this->cstr=new char[R.len+1];
strcpy(this->cstr,R.cstr);
this->len=R.len;
}
return *this;
}
my_string &operator+(const my_string &R) //运算符重载+,字符串加字符串
{
strcat(this->cstr,R.cstr);
this->len+=R.len;
return *this;
}
my_string &operator+(const char ch) //运算符重载+,字符串加字符
{
this->len+=1;
this->cstr[this->len-1]=ch;
return *this;
}
bool operator==(const my_string &R)const //运算符重载==
{
return ~strcmp(this->cstr,R.cstr);
}
bool operator!=(const my_string &R)const //运算符重载!=
{
return strcmp(this->cstr,R.cstr);
}
bool operator>(const my_string &R)const //运算符重载>
{
return ~strcmp(this->cstr,R.cstr);
}
bool operator<(const my_string &R)const //运算符重载<
{
return strcmp(this->cstr,R.cstr);
}
};
istream &operator>>(istream &L,my_string &R)
{
if(R.cstr!=NULL)
{
L>>R.cstr;
R.len=strlen(R.cstr);
}
else
{
R.cstr=new char[20];
L>>R.cstr;
R.len=strlen(R.cstr);
}
return L;
}
ostream &operator<<(ostream &L,my_string &R)
{
L<<R.cstr;
return L;
}
int main()
{
my_string s; //s调用无参构造
cout<<"请输入一个字符串:";
cin>>s; // >>运算符重载
cout<<"s: "<<s<<endl; // <<运算符重载
my_string s1("helloya"); //s1调用有参构造
cout<<"s1: "<<s1<<endl; // <<运算符重载
my_string s2; //s2调用无参构造
s2=s; // =运算符重载
cout<<"s2=s: "<<s2<<endl;
if(s1!=s2) // !=运算符重载
{
cout<<"s1和s2不相等"<<endl;
if((s1>s2)>0) // >运算符重载
{
cout<<"s1大于s2"<<endl;
}else
{
cout<<"s1小于s2"<<endl;
}
}else
{
cout<<"s1和s2相等"<<endl;
}
cout<<"s2+'h': "<<s2+'h'<<endl; // +运算符重载
cout<<"s1+s2: "<<s1+s2<<endl; // +运算符重载
return 0;
}