#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
class Mystring
{
public:
Mystring()
{ //无参构造函数
len = 0;
str = nullptr;
}
Mystring(const char* p) //有参构造函数
{
len = strlen(p);
str = new char[len+1];
strcpy(str,p);
// cout<<"有参构造函数"<<endl;
// cout<<str<<endl;
}
//拷贝构造函数
Mystring(Mystring &other):len(other.len),str(new char[other.len])
{
strcpy(str,other.str);
}
//拷贝赋值函数
Mystring& operator = (const Mystring& other)
{
if(&other != this)
{
len = other.len;
if(nullptr == str)
{
str = new char[len+1];
}
delete []str;
str = new char[len+1];
str = other.str;
}
return *this;
}
~Mystring(){ //析构函数
if( nullptr != str)
{
delete []str;
}
}
//data
char* data()
{
return str;
}
//size
int size()
{
return len;
}
//empty
bool empty()
{
return len==0;
}
//at
char& at(int index)
{
if(index<0 || index>len)
{
cout<<index<<"不合法"<<endl;
return str[0];
}
return str[index];
}
Mystring& operator+(const Mystring& R)
{
strcat(str,R.str);
return *this;
}
const bool operator!=( Mystring& R)
{
return strcmp(str,R.str)!=0;
}
const bool operator==( Mystring& R)
{
return strcmp(str,R.str)==0;
}
const bool operator<( Mystring& R)
{
return strcmp(str,R.str)<0;
}
const bool operator<=( Mystring& R)
{
return strcmp(str,R.str)<=0;
}
const bool operator>( Mystring& R)
{
return strcmp(str,R.str)>0;
}
const bool operator>=( Mystring& R)
{
return strcmp(str,R.str)>=0;
}
friend ostream& operator<<(ostream& L,const Mystring& R);
friend istream& operator>>(istream& L, Mystring& R);
private:
int len;
char * str;
};
ostream& operator<<(ostream& L,const Mystring& R)
{
Mystring s;
s.str= new char[(R.len)+1];
L<<strcpy(s.str,R.str)<<endl;
return L;
}
istream& operator>>(istream& L, Mystring& R)
{
cout<<"输入字符串>>>"<<endl;
R.str = new char[(R.len)+1];
L>>R.str;
return L;
}
int main(int argc, const char *argv[])
{
Mystring s1,s4,s5;
cin>>s1>>s4;
cout<<s1<<s4;
s5 = s1+s4;
cout<<s5;
bool ret1 = s1==s4;
cout<<ret1<<endl;
bool ret2 = s1<s4;
cout<<ret2<<endl;
bool ret3 = s1<=s4;
cout<<ret3<<endl;
bool ret4 = s1>s4;
cout<<ret4<<endl;
bool ret5 = s1>=s4;
cout<<ret5<<endl;
bool ret6 = s1!=s4;
cout<<ret6<<endl;
return 0;
}
c++ string (operator改写)
最新推荐文章于 2024-09-16 17:46:36 发布