string类
class my_string{
public:
my_string():str(NULL),len(0){
} //无参构造
my_string(const char *str):str(new char[strlen(str)+1]),len(strlen(str)){
strcpy(this->str,str);
} //有参构造
my_string(const my_string &other):str(new char[strlen(other.str)]+1),len(strlen(other.str)){
strcpy(str,other.str);
} //拷贝构造
char* show(){
return str;
}
bool empty(){
if(len>0){
return false;
}else{
return true;
}
} //判断是否为空
int size(){
return len;
} //返回字符串的长度
char &at(int index){
if(index<=len&&index>0)
return this->str[index-1];
} //定位函数
char* c_str(){
return this->str;
} //转化为C风格字符串
const my_string operator+(const my_string& s) const{ //重载 + 运算符
my_string temp;
temp.str=new char[strlen(s.str)+strlen(this->str)+1];
strcpy(temp.str,this->str);
strcat(temp.str,s.str);
return temp;
}
my_string& operator=(const my_string& s){
if(this->str!=NULL){ //如果之前str中有数据,先释放
delete []this->str;
this->str=NULL;
}
this->str=new char[strlen(s.str)+1];
strcpy(this->str,s.str);
return *this;
}
my_string& operator+=(const my_string &s){ //重载 +=
my_string temp; //用temp储存 this->str中的值
if(this->str!=NULL){ //如果this->str 中有值,便释放,之后重新开辟空间
temp=new char[strlen(this->str)+1];
strcpy(temp.str,this->str);
delete []this->str;
this->str=NULL;
}
this->str=new char[strlen(temp.str)+strlen(s.str)+1];
strcpy(this->str,temp.str);
strcat(this->str,s.str);
return *this;
}
const char& operator[](int pos)const{ //重载[]
return this->str[pos-1];
}
const bool operator==(const my_string& s) const{ //重载==
if((strcmp(this->str,s.str))==0){
return true;
}else{
return false;
}
}
const bool operator>(const my_string& s) const{ //重载>
if((strcmp(this->str,s.str))>0){
return true;
}else{
return false;
}
}
const bool operator<(const my_string& s)const{ //重载<
if((strcmp(this->str,s.str))<0){
return true;
}else{
return false;
}
}
const bool operator>=(const my_string& s)const{ //重载>=
if((strcmp(this->str,s.str))>=0){
return true;
}else{
return false;
}
}
const bool operator<=(const my_string& s)const{ //重载<=
if((strcmp(this->str,s.str))<=0){
return true;
}else{
return false;
}
}
friend ostream& operator<<(ostream &out,const my_string &s);
friend istream& operator>>(istream &in,my_string &s);
~my_string(){
delete []str;
str=NULL;
} //析构函数
private:
char *str;
int len;
};
ostream& operator<<(ostream &out,const my_string &s){ //重载<<
out<<s.str;
return out;
}
istream& operator>>(istream &in,my_string& s){ //重载>>
if(s.str!=NULL){ //判断str中有没有数据 ,若有就清空
delete []s.str;
s.str=NULL;
}
char temp_buf[128];
in>>temp_buf;
s.str=new char[strlen(temp_buf)+1];
strcpy(s.str,temp_buf);
return in;
}
验证:
int main()
{
my_string s1="bbcdef";
my_string s2=s1; //调用拷贝赋值
my_string s3="a2345";
my_string s4;
s4=s1+s3; //重载=
cout<<s4<<endl; //重载<<
if(s1>s3){ //重载>
cout<<"s1 > s3"<<endl;
}else{
cout<<"s1 !> s3"<<endl;
}
my_string s5="abc";
cout<<s5[2]<<endl; //重载[]
my_string s6="123";
s5+=s6; //重载+=
cout<<s5<<endl;
cout<<"inuput::---->"<<endl;
my_string s7;
cin>>s7; //重载>>
cout<<s7<<endl;
return 0;
}