#include <iostream>
#include <cstring>
using namespace std;
class Mystring
{
private:
char *cstr;
int len;
public:
Mystring(const char *str=NULL)
{
if(str){ //有参构造
len=strlen(str);
cstr=new char[strlen(str)+1];
strcpy(cstr,str);
}else{ //无参构造
cstr=new char('\0');
len=0;
}
}
Mystring(const Mystring &other):len(other.len)//拷贝构造
{
cstr=new char[other.len+1];
strcpy(cstr,other.cstr);
}
Mystring& operator=(const Mystring &other)//拷贝赋值
{
if(this!=&other){
cstr=new char[other.len+1];
strcpy(cstr,other.cstr);
len=other.len;
}
return *this;
}
const Mystring operator+(const Mystring &other)const//实现+号运算符重载
{
Mystring temp;
temp.len=this->len+other.len;
temp.cstr=new char[temp.len+1];
strcat(temp.cstr,this->cstr);
strcat(temp.cstr,other.cstr);
return temp;
}
Mystring& operator+=(const Mystring &other)//实现+=号运算符重载
{
this->len+=other.len;
strcat(this->cstr,other.cstr);
return *this;
}
bool operator==(const Mystring &other)const//实现==号运算符重载
{
return strcmp(this->cstr,other.cstr)==0?1:0;
}
char &operator[](int i)//实现[]运算符重载
{
return this->cstr[i];
}
//将提取运算符重载函数设为友元
friend istream& operator>>(istream &L,Mystring &R);
//将插入运算符重载函数设为友元
friend ostream& operator<<(ostream &L,const Mystring &R);
//将getline重载函数设为友元
friend istream& getline(istream& is, Mystring& s);
~Mystring() //析构函数
{
delete []cstr;
cout<<"析构函数"<< " 析构地址为:"<< this <<endl;
}
bool empty() //判断是否为空
{
if(len==0)
{
return 0;
}
else
{
return 1;
}
}
int size() //返回字符串的长度
{
return len;
}
char &at(int index) //定位函数
{
if(index<0 || index >= len)
{
cout<<"定位错误!"<<endl;
}
return *(cstr+index);
}
char* c_str() //转化为C风格字符串
{
return cstr;
}
void show()
{
cout<<"cstr = "<<cstr<<endl;
cout<<"len = "<<len<<endl;
}
};
//实现提取运算符重载
istream& operator>>(istream &L,Mystring &R){
L>>R.cstr;
R.len=strlen(R.cstr);
return L;
}
//实现插入运算符重载
ostream& operator<<(ostream &L,const Mystring &R){
L<<R.cstr;
return L;
}
//实现getline重载
istream& getline(istream& is, Mystring& s){
gets(s.cstr);
s.len=strlen(s.cstr);
return is;
}
void show(Mystring s)
{
cout<<"**************************"<<endl;
cout<<"字符串长度为>>>"<<s.size()<<endl;
cout<<"字符串为>>>"<<s.c_str()<<endl;
}
int main()
{
Mystring s = "good time";
show(s);
Mystring s1 = "hello world";
show(s1);
Mystring s3=s+s1;
show(s3);
if(s1==s)//测试==运算符
cout<<"s和s1相等"<<endl;
else
cout<<"s1和s不相等"<<endl;
Mystring s4;
cout<<"(cin)请输入s4>>";
cin>>s4;//测试提取运算符
while(getchar()!=10);
show(s4);
cout<<s4<<endl;//测试插入运算符
for(int i=0;i<s4.size();i++)
printf("s4[%d]=%c ",i,s4[i]);//测试[]运算符
cout<<endl;
Mystring s5="12345";
s5+=s;//测试+=运算符
show(s5);
Mystring s6;
cout<<"(getline)请输入s6>>";
getline(cin,s6);//测试getline
show(s6);
cout<<s6<<endl;
return 0;
}
C++仿照string类实现自定义My_strng类
于 2022-12-06 21:17:19 首次发布