## 作业:
在昨天my_string的基础上,将能重载的运算符全部重载掉
关系运算符:>、<、==、>=、<=、!=
加号运算符:+
取成员运算符:[]
赋值运算符: =
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
//无参构造函数
my_string()
{
cout<<"no"<<endl;
}
//有参构造函数
my_string(char *a)
{
len = length(a);
str = new char[len];
for(int i=0;i<len;i++)
{
str[i] = *(a+i);
}
cout<<"have"<<endl;
}
//拷贝构造函数
my_string(const my_string& s)
{
len = s.len;
str = new char[len];
for(int i=0;i<len;i++)
{
str[i] = s.str[i];
}
cout<<"copy over"<<endl;
}
//拷贝赋值函数
my_string& operator =(const my_string& s)
{
len = s.len;
str = new char[len];
for(int i=0;i<len;i++)
{
str[i] = s.str[i];
}
return *this;
}
//析构函数
~my_string()
{
delete []str;
}
//show
void show()
{
cout<<"str="<<str<<'\t'<<"len="<<len<<endl;
}
//判空
void if_empty()
{
if(len == 0)
{
cout<<"empty"<<endl;
}
else
{
cout<<"have number"<<endl;
}
}
//求长度
int length(char *a)
{
len = 0;
while(*a != '\0')
{
len++;
a++;
}
cout<<"len="<<len<<endl;
return len+1;
}
//转化为C语言字符串
// void c_lang()
// {
// str[len+1] = '\0';
// }
// friend my_string operator [](my_string& a);
friend my_string& operator +=(my_string& a, my_string& b);
friend my_string operator +(my_string&a, my_string& b);
friend bool operator >(my_string&a, my_string& b);
friend bool operator <(my_string&a, my_string& b);
friend bool operator ==(my_string&a, my_string& b);
};
//my_string operator [](my_string& a)
//{
// return a.str[num];
//}
my_string& operator +=(my_string& a, my_string& b)
{
a.len -= 1;
for(int i=0;i<b.len;i++)
{
a.str[a.len] = b.str[i];
a.len++;
}
return a;
}
my_string operator +(my_string& a, my_string& b)
{
my_string temp;
temp.len = a.len + b.len - 1;
//temp.str = new char[temp.len];
int i=0;
for(i=0;i<a.len-1;i++)
{
temp.str[i] = a.str[i];
}
for(int j=0;j<b.len;j++)
{
temp.str[i] = b.str[j];
i++;
}
return temp;
}
bool operator >(my_string&a, my_string& b)
{
if(strcmp(a.str, b.str) > 0)
return true;
else
return false;
}
bool operator <(my_string&a, my_string& b)
{
if(strcmp(a.str, b.str) < 0)
return true;
else
return false;
}
bool operator ==(my_string&a, my_string& b)
{
if(strcmp(a.str, b.str) == 0)
return true;
else
return false;
}
int main()
{
// my_string s1("aaa"); //have
// s1.show();
// s1.if_empty();
// my_string s2; //no
// s2 = s1; //copy =
// s2.show();
// s1.if_empty();
// my_string s3 = s2;
// s3.show();
// s1.if_empty();
cout<<"-------------"<<endl;
my_string a1("abc");
my_string a2("def");
my_string a3;
a3 = a1 + a2;
a3.show();
a1 += a2;
a1.show();
my_string s1("aaa");
my_string s2("aaa");
cout<<"s1>s2 "<<(s1>s2?"Yes":"No")<<endl;
cout<<"s1<s2 "<<(s1<s2?"Yes":"No")<<endl;
cout<<"s1=s2 "<<(s1==s2?"Yes":"No")<<endl;
return 0;
}