实现Mystring类
#include <iostream>
#include <cstring>
using namespace std;
class Mystring
{
private:
int len;
char *str; //记录c风格的字符串
public:
//无参构造
Mystring() :len(10)
{
str = new char[len];
strcpy(str, "");
}
//有参构造
Mystring(const char *s)
{
len = strlen(s);
str = new char[len+1];
strcpy(str,s);
}
//定义拷贝构造函数
Mystring(const Mystring &other) //深拷贝
{
len = other.len;
str = new char[len+1];
strcpy(str,other.str);
}
//定义拷贝赋值函数
Mystring & operator=(const Mystring &other)
{
if(this != &other)
{
this->len = other.len;
strcpy(this->str,other.str);
}
return *this;
}
//定义析构函数
~Mystring()
{
delete[] str;
}
//定义判空函数
bool empty()
{
return strlen(str) == 0;
}
//定义size函数
int size()
{
return strlen(str);
}
//定义c_str函数
char *c_str()
{
return str;
}
//定义at函数
char &at(int pos)
{
if(pos < 0 || pos > len)
{
cout<<"越界"<<endl;
}
return str[pos];
}
//operator[]
char &operator[](int pos)
{
return str[pos];
}
//operator+
const Mystring operator+(const Mystring &R)const
{
//定义临时变量
Mystring temp;
temp.len = this->len + R.len;
temp.str = new char[temp.len + 1];
strcpy(temp.str,this->str);
strcat(temp.str,R.str);
return temp;
}
//operator==
bool operator==(const Mystring &R)const
{
return strcmp(this->str,R.str) == 0;
}
//operator!=
bool operator!=(const Mystring &R)const
{
return strcmp(this->str,R.str);
}
//operator<
bool operator<(const Mystring &R)const
{
return strcmp(this->str,R.str) < 0;
}
//operator>
bool operator>(const Mystring &R)const
{
return strcmp(this->str,R.str) > 0;
}
//operator<=
bool operator<=(const Mystring &R)const
{
return strcmp(this->str,R.str) <= 0;
}
//operator>=
bool operator>=(const Mystring &R)const
{
return strcmp(this->str,R.str) >= 0;
}
friend ostream &operator<<(ostream &L, const Mystring &R);
friend istream &operator>>(istream &L, const Mystring &R);
};
//全局函数实现字符串的输入输出
//operator<<
ostream &operator<<(ostream &L, const Mystring &R)
{
L<<R.str<<endl;
return L;
}
//operator>>
istream &operator>>(istream &L, const Mystring &R)
{
L>>R.str;
return L;
}
int main()
{
Mystring s1;
Mystring s2("hello");
Mystring s3("world");
s2[0] = 'H';
Mystring s4;
s4 = s2 + s3;
cout<<s4<<endl;
Mystring s5;
cin>>s5;
cout<<s5<<endl;
cout <<s5.size() << endl;
return 0;
}