
代码:
#include <iostream>
#include <cstring>
using namespace std;
class mystring
{
private:
char *str;
int size;
public:
mystring() {};
mystring(const char *s)
{
size = strlen(s); //求出字符串s的实际长度
str = new char[size +1]; //申请size+1个char类型的空间大小
strcpy(str,s);
}
//拷贝复制函数
mystring &operator= (const mystring &R) //拷贝复制函数
{
if(this != &R)
{
delete []str;
this->size = R.size;
str = new char[this->size +1];
strcpy(str,R.str);
}
return *this;
}
char *c_str()
{
return str;
}
//实现operator[]运算符重载功能
char &operator[] (int pos) const
{
if(pos >= 0 && pos < size)
{
return str[pos];
}else
{
cout<<"下标越界"<<endl;
}
return str[pos];
}
//实现operator+运算符重载功能
const mystring operator+ ( const mystring &other) const
{
mystring temp;
temp.size = this->size + other.size;
temp.str = new char[temp.size +1];
strcpy(temp.str,str);
strcat(temp.str,other.str);
return temp;
}
//实现operator==运算符重载功能
bool operator==(const mystring &other)const
{
if(this->size != other.size) //判断两个字符串的字节长度是否相同
{
return false;
}
return strcmp(this->str,other.str) == 0 ;
}
//实现operator!=运算符重载功能
bool operator!=(const mystring &other)const
{
return strcmp(this->str,other.str) != 0 ;
}
//实现operator< 运算符重载功能
bool operator<(const mystring &other)const
{
return strcmp(this->str,other.str) < 0;
}
//实现operator< 运算符重载功能
bool operator>(const mystring &other)const
{
return strcmp(this->str,other.str) > 0;
}
//实现operator<=运算符重载功能
bool operator<=(const mystring &other)const
{
return strcmp(this->str,other.str) <= 0;
}
//实现operator>=运算符重载功能
bool operator>=(const mystring &other)const
{
return strcmp(this->str,other.str) >= 0;
}
//实现operator<<输出功能
friend ostream &operator<<(ostream &L,const mystring &R);
//实现operator>>输出功能
friend istream &operator>>(istream &L,const mystring &R);
};
ostream &operator<<(ostream &L,const mystring &R)
{
L << R.str;
return L;
}
istream &operator>>(istream &L,const mystring &R)
{
L >> R.str;
return L;
}
int main()
{
mystring s1("hello");
cout<<"s1 = "<<s1.c_str()<<endl;//实现函数有参构造
mystring s2;
s2 = s1;
cout<<"s2 = "<<s2.c_str()<<endl; //实现拷贝复制功能
mystring s3(" world");
s1 = s1+s3;
cout<<"s1 = "<<s1.c_str()<<endl; //实现字符串拼接功能
if(s1 == s3) //判断两个字符串之间是否相等
{
cout<<"Yes"<<endl;
}else
{
cout<<"No"<<endl;
}
if(s1 != s3) //判断两个字符串之间是否不等
{
cout<<"Yes"<<endl;
}else
{
cout<<"No"<<endl;
}
if(s1 < s3) //判断两个字符串之间的大小
{
cout<<"Yes"<<endl;
}else
{
cout<<"No"<<endl;
}
if(s1 > s3) //判断两个字符串之间的大小
{
cout<<"Yes"<<endl;
}else
{
cout<<"No"<<endl;
}
if(s1 <= s2) //判断两个字符串之间的大小
{
cout<<"Yes"<<endl;
}else
{
cout<<"No"<<endl;
}
if(s1 >= s3) //判断两个字符串之间的大小
{
cout<<"Yes"<<endl;
}else
{
cout<<"No"<<endl;
}
cout<<s1<<endl;
cin>>s1;
cout<<s1;
return 0;
}
文章展示了一个C++自定义字符串类`mystring`的实现,包括构造函数、拷贝构造函数、赋值运算符`=`重载、成员函数`c_str()`以及一系列表达式运算符如`+`,`==`,`!=`,`<`,`>`,`<=`,`>=`的重载。此外,还展示了如何使用这些功能进行字符串操作,如构造、复制、拼接和比较。
1205

被折叠的 条评论
为什么被折叠?



