关系运算符:>、<、==、>=、<=、!=
加号运算符:+
取成员运算符:[]
#include <iostream>
#include<string.h>
using namespace std;
class my_string
{
public:
//无参构造
my_string(){}
~my_string(){delete str;}
//有参构造
my_string(char *s)
{
str=new char[128];
strcpy(str,s);
}
//拷贝构造
my_string(const my_string& o)
{
this->str=new char[128];
strcpy(this->str,o.str);
this->len=o.len;
}
//拷贝赋值
my_string& operator =(const my_string& r)
{
this->str=new char[128];
strcpy(this->str,r.str);
this->len=r.len;
}
//+
const my_string operator+(my_string &o)
{
this->len=strlen(strcat(this->str,o.str));
return *this;
}
//>
bool operator>(my_string& o)
{
if(strcmp(this->str,o.str)>0)
return true;
else
return false;
}
//<
bool operator<(my_string& o)
{
if(strcmp(this->str,o.str)<0)
return true;
else
return false;
}
//==
bool operator==(my_string& o)
{
if(strcmp(this->str,o.str)==0)
return true;
else
return false;
}
bool my_empty() // 判空
{
if(strlen(str)==0)
return true;
else
return false;
}
//>=
bool operator>=(my_string& o)
{
if(strcmp(this->str,o.str)>=0)
return true;
else
return false;
}
//<=
bool operator<=(my_string& o)
{
if(strcmp(this->str,o.str)<=0)
return true;
else
return false;
} //!=
bool operator!=(my_string& o)
{
if(strcmp(this->str,o.str)!=0)
return true;
else
return false;
}
char operator[](int o)
{
return this->str[o];
}
int my_size() // 求长度
{
return strlen(str);
}
char *my_str() // 转化为c风格字符串
{
return str;
}
private:
char *str;
int len;
};
int main(int argc,const char* argv[])
{
my_string s1("hello");
cout<<"s1:"<<s1.my_str()<<endl;
my_string s2=s1;
cout<<"s2:"<<s2.my_str()<<endl;
my_string s3;
s3=s1;
cout<<"s3:"<<s3.my_str()<<endl;
if(s3.my_empty())
{
cout<<"kong"<<endl;
}
else
{
cout<<"not kong"<<endl;
}
int len=s1.my_size();
cout<<"len="<<len<<endl;
my_string s4("abc");
cout << "s4>s1:" << (s4 > s1 ? "yes" : "no") << endl;
cout << "s4<s1:" << (s4 < s1 ? "yes" : "no") << endl;
cout << "s4==s1:" << (s4 == s1 ? "yes" : "no") << endl;
cout << "s4>=s1:" << (s4 >= s1 ? "yes" : "no") << endl;
cout << "s4<=s1:" << (s4 <= s1 ? "yes" : "no") << endl;
cout << "s4!=s1:" << (s4 != s1 ? "yes" : "no") << endl;
s4 = s4 + s1;
cout << "s4 + s1=";
cout<<s4.my_str()<<endl;
return 0;
}