📄 mystring.cpp
字号:
#include<iostream>
using namespace std;
#include<cstring>
class mystring;
bool operator<=(const mystring&s1,const mystring&s2);
bool operator>(const mystring&s1,const mystring&s2);
bool operator==(const mystring&s1,const mystring&s2);
ostream operator<<(ostream &os,const mystring& rhs);
istream operator>>(istream &is,mystring& rhs);
class mystring{
private:
char *str;
int len;
enum {CINLIM=80} ;
public:
mystring();
mystring(const mystring& rhs);
~mystring();
mystring(const char*s);
int length(){return len;}
mystring& operator=(const mystring&rhs);
mystring& operator=(const char*s);
mystring& operator+=(const mystring& rhs);
char& operator[](int i);
const char& operator[](int i)const;
friend bool operator<=(const mystring&s1,const mystring&s2);
friend bool operator>(const mystring&s1,const mystring&s2);
friend bool operator==(const mystring&s1,const mystring&s2);
friend ostream operator<<(ostream &os,const mystring& rhs);
friend istream operator>>(istream &is,mystring& rhs);
};
mystring::mystring(){
len=0;
str=new char[1];
str[0]='\0';
}
mystring::mystring(const mystring& rhs){
len=rhs.len;
str=new char[len+1];
strcpy(str,rhs.str);
}
mystring::~mystring(){
delete []str;
str=NULL;
len=0;
}
mystring::mystring(const char* s){
len=strlen(s);
str=new char[len+1];
strcpy(str,s);
}
mystring& mystring::operator+=(const mystring& rhs){
len=len+rhs.len ;
char* temp=new char[len+1];
int i;
for(i=0;str[i]!='\0';i++)
temp[i]=str[i];
for(int j=0;j<rhs.len ;j++)
temp[i+j]=rhs.str [j];
temp[len]='\0';
delete []str;
str=temp;
return *this;
}
mystring& mystring::operator=(const mystring& rhs){
if(this==&rhs) return *this;
delete []str;
len=rhs.len;
str=new char[len+1];
strcpy(str,rhs.str);
return *this;
}
mystring& mystring::operator=(const char* s){
delete []str;
len=strlen(s);
str=new char[len+1];
strcpy(str,s);
return *this;
}
char& mystring::operator[](int i){
return str[i-1];
}
const char& mystring::operator[](int i)const{
return str[i-1];
}
bool operator<=(const mystring&s1,const mystring& s2){
return(strcmp(s1.str,s2.str)<=0);
}
bool operator>(const mystring&s1,const mystring& s2){
return(strcmp(s1.str,s2.str)>0);
}
bool operator==(const mystring&s1,const mystring& s2){
return(strcmp(s1.str,s2.str)==0);
}
ostream operator<<(ostream &os,const mystring& rhs){
os<<rhs.str;
return os;
}
istream operator>>(istream &is,mystring& rhs){
char temp[mystring::CINLIM];
is.get(temp,mystring::CINLIM);
if(is){
delete []rhs.str;
rhs.len=mystring::CINLIM;
rhs.str=new char[mystring::CINLIM+1];
strcpy(rhs.str,temp);
}
while(is&&is.get()!='\n')
continue;
return is;
}
int main(){
mystring s1,s2;
s1="3111111";
s2="1223233";
cout<<"s1="<<s1<<endl;
s2+=s1;
cout<<"s2="<<s2<<endl;
cout<<(s1<=s2)<<endl;
cout<<s2.length ()<<endl;
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -