在昨天my_string的基础上,将能重载的运算符全部重载掉
关系运算符:>、<、==、>=、<=、!=
加号运算符:+
取成员运算符:[]
赋值运算符: =
C++代码
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
class my_string
{
public:
//无参构造
my_string(){};
//有参构造
my_string(char *str):str(str)
{
len = my_size(str);
};
//拷贝构造
my_string(my_string &buf):str(buf.str)
{
len = my_size(str);
}
//拷贝赋值
my_string& operator=(const my_string& R)
{
if(this != &R)
{
this->str = new char(*R.str);
len = my_size(str);
}
return *this;
}
//bool my_empty()
bool my_empty(char* str)
{
if(my_size(str) == 0)
{
return 1;
}
else
{
return 0;
}
}
//int my_size()
int my_size(char* str)
{
int i=0;
while(str[i]!= '\0')
{
i++;
}
return i;
}
//char* my_str()
char* my_str()
{
return str;
}
//输出
void pop()
{
cout<<"str:"<<str<<endl;
cout<<"len:"<<len<<endl;
cout<<"empty?"<<endl;
if(my_empty(str) == 0)
{
cout<<"not empty"<<endl<<endl;
}
else
{
cout<<"is empty"<<endl<<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&);
char operator[](int i)
{
return this->str[i];
}
friend my_string operator+(my_string&,my_string&);
friend ostream& operator<<(ostream&,my_string&);
friend istream& operator>>(istream&,my_string&);
private:
char *str;
int len;
};
my_string operator+(my_string&L,my_string&R)
{
strcat(L.str,R.str);
return L;
}
istream& operator>>(istream& input,my_string&R)
{
input>>R.str;
input>>R.len;
return input;
}
ostream& operator<<(ostream& output,my_string&R)
{
output<<R.str;
output<<R.str;
return output;
}
bool operator<(my_string&L,my_string&R)
{
if(strcmp(L.str,R.str)<0)
{
return true;
}
else
{
return false;
}
}
bool operator>(my_string&L,my_string&R)
{
if(strcmp(L.str,R.str)>0)
{
return true;
}
else
{
return false;
}
}
bool operator!=(my_string&L,my_string&R)
{
if(strcmp(L.str,R.str)!=0)
{
return true;
}
else
{
return false;
}
}
bool operator==(my_string&L,my_string&R)
{
if(strcmp(L.str,R.str)!=0)
{
return true;
}
else
{
return false;
}
}
int main()
{
my_string str1("hello");
cout<<"str1>>>"<<endl;
str1.pop();
my_string str2(str1);
cout<<"str2>>>"<<endl;
str2.pop();
my_string str3=str2;
cout<<"str3>>>"<<endl;
str3.pop();
my_string str4("my world");
str4.pop();
return 0;
}