目录
代码:
#include <iostream>
#include <string>
#include<string.h>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
//无参构造
my_string(){
str = new char[128];
memset(str,0,128);
}
//有参构造
my_string(char *s,int l)
{
str = s;
len = l;
}
//拷贝构造
my_string(const my_string &m)
{
this->len = m.len;
this->str = m.str;
}
//拷贝赋值
my_string &operator = (const my_string &r)
{
if(this != &r)
{
this->len=r.len;
this->str = r.str;
}
return *this;
}
//输出
void display()
{
for(int i=0;i<strlen(str);i++)
{
cout<<*(str+i);
}
cout<<'\t'<<len<<endl;
}
friend bool operator>(my_string &,my_string &);
friend bool operator<(my_string &,my_string &);
friend bool operator==(my_string &,my_string &);
friend bool operator>=(my_string &,my_string &);
friend bool operator<=(my_string &,my_string &);
friend bool operator!=(my_string &,my_string &);
//赋值运算符 ‘=‘
my_string &operator=(my_string &R)
{
this->str=R.str;
this->len=R.len;
return *this;
}
//取成员运算符:[]
char operator[](const int index)
{
return (this->str)[index];
}
//加号运算符:+
my_string &operator+(my_string &R)
{
my_string tmp;
strcat(tmp.str,this->str);
strcat(tmp.str,R.str);
tmp.len=this->len+R.len;
return tmp;
}
};
//关系运算符:>
bool operator>(my_string &L,my_string &R)
{
if(L.str>R.str)
{return true;}
else
{return false;}
}
//关系运算符:<
bool operator<(my_string &L,my_string &R)
{
if(L.str<R.str)
{return true;}
else
{return false;}
}
//关系运算符:==
bool operator==(my_string &L,my_string &R)
{
if(L.str==R.str)
{return true;}
else
{return false;}
}
//关系运算符:>=
bool operator>=(my_string &L,my_string &R)
{
if(L.str>=R.str)
{return true;}
else
{return false;}
}
//关系运算符:<=
bool operator<=(my_string &L,my_string &R)
{
if(L.str<=R.str)
{return true;}
else
{return false;}
}
//关系运算符:!=
bool operator!=(my_string &L,my_string &R)
{
if(L.str != R.str)
{return true;}
else
{return false;}
}
int main()
{
my_string s1("how are you",12),s2("hello world",20);
cout<<"s1>s2?"<<'\t'; cout<<(s1>s2?"true":"false")<<endl;
cout<<"s1<s2?"<<'\t'; cout<<(s1<s2?"true":"false")<<endl;
cout<<"s1==s2?"<<'\t'; cout<<(s1==s2?"true":"false")<<endl;
cout<<"s1>=s2?"<<'\t'; cout<<(s1>=s2?"true":"false")<<endl;
cout<<"s1<=s2?"<<'\t'; cout<<(s1<=s2?"true":"false")<<endl;
cout<<"s1!=s2?"<<'\t'; cout<<(s1!=s2?"true":"false")<<endl;
my_string s3 = s1+s2;
s3.display();
cout<<s1[2]<<endl;
return 0;
}
执行结果: