自己写的string类
#include <iostream>
using namespace std;
class String
{
char *ptr;
public:
String();
~String();
explicit String(const char *p);
String(const String&s);
String& operator=(const String& rhs);
friend ostream&operator<<(ostream& os,const String& s);
};
String::String()
{
ptr=new char[1];
ptr[0]='\0';
}
String::~String()
{
delete[]ptr;
}
String::String(const char*p)
{
ptr=new char[strlen(p)+1];
strcpy(ptr,p);
}
String::String(const String&s)
{
ptr=new char[strlen(s.ptr)+1];
strcpy(ptr,s.ptr);
}
String& String::operator=(const String& rhs)
{
if(this!=&rhs)
{
delete[]ptr;
ptr=new char[strlen(rhs.ptr)+1];
strcpy(ptr,rhs.ptr);
}
return *this;
}
ostream&operator<<(ostream& os,const String& s)
{
os<<s.ptr;
return os;
}
int main()
{
String s1;
String s2("abcd");
String s3=s2;
s1=s2;
s2=s2;
cout<<s2<<endl;
system("pause");
return 0;
}