在my_string的基础上,将能重载的运算符全部重载掉
关系运算符:>、<、==、>=、<=、!=
加号运算符:+
取成员运算符:[]
赋值运算符: =
#include <iostream>
#include <string.h>
using namespace std;
class my_string
{
private:
char *str=NULL;
int len;
public:
// 无参构造
my_string(){
str=NULL;
len=0;
}
// 有参构造
my_string(const char *newstr)
{
len=strlen(newstr);
str=new char[len+1];
strcpy(str,newstr);
}
my_string(int l,char c)
{
len=l;
str=new char[len+1];
char *rp=str;
for(int i=0;i<len;i++){
*rp=c;
rp++;
}
*rp=0;
}
// 拷贝构造
my_string(const my_string& sa):len(sa.len) // 添加const
{ // +运算符通过生成临时变量传回局部变量temp
str=new char[len+1]; // 接收临时变量需要加const
strcpy(str,sa.str);
}
// 拷贝赋值
my_string& operator=(my_string& R)
{
len=R.len;
if(str){
delete str;
}
str=new char[len+1];
strcpy(str,R.str);
return *this;
}
my_string& operator=(const char* oldstr)
{
len=strlen(oldstr);
if(str){
delete str;
}
str=new char[len+1];
strcpy(str,oldstr);
return *this;
}
// bool my_empty() 判空
bool my_empty()
{
return len?true:false;
}
// int my_size() 求长度
int my_size()
{
return len;
}
// char *my_str() 转化为c风格字符串
char *my_str()
{
return str;
}
~my_string()
{
if(str)
delete str;
}
void str_show()
{
cout<<str;
}
// >
bool operator>(my_string& L)
{
if(strcmp(str,L.str)>0){
return true;
}else{
return false;
}
}
// <
bool operator<(my_string& L)
{
if(strcmp(str,L.str)<0){
return true;
}else{
return false;
}
}
// ==
bool operator==(my_string& L)
{
if(strcmp(str,L.str)==0){
return true;
}else{
return false;
}
}
// >=
bool operator>=(my_string& L)
{
if(strcmp(str,L.str)>=0){
return true;
}else{
return false;
}
}
// <=
bool operator<=(my_string& R)
{
if(strcmp(str,R.str)<=0){
return true;
}else{
return false;
}
}
// !=
bool operator!=(my_string& R)
{
if(strcmp(str,R.str)!=0){
return true;
}else{
return false;
}
}
// +
my_string operator+(my_string& R)
{
my_string temp;
temp.str=new char[len+R.len+1]; // +运算结束后释放temp时析构函数内释放
temp.len=len+R.len;
strcpy(temp.str,str);
strcat(temp.str,R.str);
temp.str[len+R.len]=0;
return temp;
}
// =
my_string& operator=(my_string R)
{
if(str){
delete str;
}
str=new char[len+1];
strcpy(str,R.str);
str[len]=0;
len=R.len;
return *this;
}
// []
char operator[](int n)
{
if(n<0 || n>=len){
cout<<"坐标错误"<<endl;
return 0;
}else{
return str[n];
}
}
// =
// 拷贝赋值
friend ostream& operator<<(ostream& out,my_string& O);
};
ostream& operator<<(ostream& out, my_string& O)
{
out<<O.my_str();
return out;
}
int main()
{
my_string s1("abcde");
cout<<"s1:";
s1.str_show();
cout<<endl;
my_string s2("abcdf");
cout<<"s2:";
s2.str_show();
cout<<endl;
cout<<"s1>s2:";
cout<<(s1>s2);
cout<<endl;
cout<<"s1<s2:";
cout<<(s1<s2);
cout<<endl;
cout<<"s1==s2:";
cout<<(s1==s2);
cout<<endl;
cout<<"s1>=s2:";
cout<<(s1>=s2);
cout<<endl;
cout<<"s1<=s2:";
cout<<(s1<=s2);
cout<<endl;
cout<<"s1!=s2:";
cout<<(s1!=s2);
cout<<endl;
cout<<"s1+s2:";
my_string s3=s1+s2;
cout<<s3;
cout<<endl;
cout<<"s1[3]";
cout<<s1[3];
cout<<endl;
cout<<"s1=\"123456\"\ns1:";
s1="123456";
cout<<s1;
cout<<endl;
return 0;
}