重载字符串使之加减赋值

#include #include class String {

public: char *str; public: String(char *p=NULL); String(String & p); ~String(); public: String operator +=(char *p); String operator +=( const String &p); friend String operator +(const String &c1, const String &c2); String&operator=(const String&p); String&operator=(char*P); String operator-(const String&other); void print(); };

void String::print() { cout<

String::String(char *p) { if(p) { int nlen=strlen(p)+1; str=new char[nlen]; strcpy(str,p); } else str=new char[1]; *str='\\0'; }

String::String(String & p ) { if(p.str) { int nlen=strlen(p.str)+1; str=new char[nlen]; strcpy(str,p.str);

} else str=NULL; }

String::~String() { if(str) delete[]str; }

String String::operator +=(char *p) { char *q; int n=strlen(str)+1; q=new char[n]; strcpy(q,str); if(str) delete[]str; int nlen=strlen(q)+strlen(p)+1; str=new char[nlen]; strcpy(str,q); strcat(str,p); return *this; }

String String::operator +=(const String&p) { char *q; int n=strlen(str)+1; q=new char[n]; strcpy(q,str); if(str) delete[]str; int nlen=strlen(q)+strlen(p.str)+1; str=new char[nlen]; strcpy(str,q); strcat(str,p.str); return *this; }

String operator +(const String &c1, const String &c2) { String ff;

int nlen=strlen(c1.str )+strlen(c2.str)+1; ff.str=new char[nlen]; strcpy(ff.str,c1.str); strcat(ff.str,c2.str );

return ff; }

String &String::operator =(const String&p) { if(p.str) { int nlen=strlen(p.str)+1; str=new char[nlen]; strcpy(str,p.str); } else str=NULL; return *this; }

String& String::operator =(char *p) { if(p) { int nlen=strlen(p)+1; str=new char[nlen]; strcpy(str,p); } else str=NULL; return *this; }

String String::operator -(const String&other) { char *temp,*p; if((temp=strstr(str,other.str))==NULL) { cout<<\没有符合的子串,不能使用'-'操作\ return *this; } else { p=temp; temp=temp+strlen(other.str); *p='\\0'; strcat(str,temp); return *this; } }

void main()

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4