#include <iostream>
#include <cstring>
using namespace std;
class My_string
{
private:
char* cstr;
int len;
public:
//无参构造
My_string():cstr(NULL),len(0)
{
//cout << "无参构造" << endl;
}
//有参构造
My_string(const char* str)
{
this->len = strlen(str);
this->cstr = new char[strlen(str)+1];
strcpy(this->cstr,str);
//cout << "有参构造" << endl;
}
//拷贝构造函数
My_string(const My_string &other)
{
this->len = other.len;
this->cstr = new char[other.len+1];
strcpy(this->cstr,other.cstr);
//cout << "拷贝构造" << endl;
}
//析构函数
~My_string()
{
if(this->cstr != NULL)
delete this->cstr;
//cout << "析构函数" << endl;
}
//判断是否为空
bool empty()
{
return this->len == 0 ? true : false;
}
//返回字符串的长度
int size()
{
return this->len;
}
//定位函数
char &at(int index)
{
return *(this->cstr+index);
}
//转化为C风格的字符串
char* c_str()
{
return this->cstr;
}
//输出函数
void StringShow()
{
cout << this->cstr << endl;
}
// 运算符重载=
My_string & operator=(My_string str)
{
this->len = str.len;
if(this->cstr == NULL)
{
this->cstr = new char[str.len+1];
}
else
{
delete this->cstr;
this->cstr = new char[str.len+1];
}
strcpy(this->cstr,str.cstr);
return *this;
}
// 运算符重载+
My_string & operator+(const char* str1)
{
this->len = this->len + strlen(str1);
strcat(this->cstr,str1);
return *this;
}
My_string & operator+(const My_string str1)const
{
static My_string temp;
temp.len = this->len + str1.len;
temp.cstr = new char[temp.len+1];
strcpy(temp.cstr,this->cstr);
strcat(temp.cstr,str1.cstr);
return temp;
}
// 运算符重载==
bool operator==(const My_string &str)
{
return (0 == strcmp(this->cstr,str.cstr)) && (this->len == str.len);
}
// 运算符重载!=
bool operator!=(const My_string &str)
{
return strcmp(this->cstr,str.cstr) && (this->len != str.len);
}
// 运算符重载<
bool operator<(const My_string &str)
{
if(*this == str)
return false;
return this->cstr < str.cstr ? true : false;
}
// 运算符重载>
bool operator>(const My_string &str)
{
if(*this == str)
return false;
return this->cstr > str.cstr ? true : false;
}
// 运算符重载<=
bool operator<=(const My_string &str)
{
if(*this == str)
return true;
return this->cstr <= str.cstr ? true : false;
}
// 运算符重载>=
bool operator>=(const My_string &str)
{
if(*this == str)
return true;
return this->cstr >= str.cstr ? true : false;
}
// 运算符重载<<
friend ostream &operator<<(ostream &l,const My_string str);
};
ostream &operator<<(ostream &l,const My_string str)
{
l << str.cstr << endl;
return l;
}
int main()
{
My_string m1("world ");
m1.StringShow();//world
My_string m2(m1);
m2.StringShow();//world
My_string m3 = m1 + " hello!";
m3.StringShow(); //world hello!
My_string m4 = "world ";
m4.StringShow();//world
My_string m5 = m4 + m3;
m5.StringShow();//world world hello!
cout << (m3==m4) << endl;//0
cout << (m3!=m4) << endl;//1
cout << (m3>m4) << endl;//0
cout << (m3<m4) << endl;//1
cout << (m3>=m4) << endl;//0
cout << (m3<=m4) << endl;//1
cout << m4 <<endl;//world
return 0;
}
仿照string类,实现自定义My_strng类,以及相关操作2
于 2022-12-07 21:00:33 首次发布