#include <iostream>
#include<string.h>
using namespace std;
class String {
char *ptr;
int len;
public:
String(char *s = NULL)
{
if(s != NULL)
{
ptr = new char[strlen(s)+1];
strcpy(ptr, s);
}
else ptr = NULL;
}
~String() { delete []ptr; }
void print() { cout<<ptr<<endl; }
String &operator=(const String&s)
{
if(&s==this)
{
return *this;
}
else
{
ptr=new char[strlen(s.ptr)+1];
strcpy(ptr,s.ptr);
return *this;
}
}
String &operator+=(String&s)
{
char*tmp=ptr;
ptr=new char[strlen(ptr)+strlen(s.ptr)+1];
strcpy(ptr,tmp);
strcat(ptr,s.ptr);
delete []tmp;
return *this;
}
friend ostream&operator<<(ostream&out,const String&s)
{
out<<s.ptr<<endl;
return out;
}
};
int main( )
{ String p1("book"), p2("pen"),p3("good"),p4;
p4 = p4 = p1 ;
p3 = p1 = p2;
cout<<"p2:";
p2.print();
cout<<"p1:"<<p1;
cout<<"p3:"<<p3;
p4+=p3;
cout<<"p4:"<<p4;
return 0;
}
重载拼接字符串
最新推荐文章于 2023-06-18 18:55:43 发布