标签:string的深拷贝
#include<iostream>
using namespace std;
class String
{
public:
char* GetChar()
{
return _ptr;
}
void swap(String&s)
{
char* tmp = s._ptr;
s._ptr = _ptr;
_ptr = tmp;
}
String(char*str)
:_ptr(new char[strlen(str) + 1])
{
strcpy(_ptr, str);
}
String(const String&s)
:_ptr(NULL)
{
String tmp(s._ptr);
swap(tmp);
}
String& operator=(const String&s)
{
if (this != &s)
{
String tmp(s._ptr);
swap(tmp);
}
return *this;
}
~String()
{
if (_ptr)
{
delete[]_ptr;
}
}
private:
char* _ptr;
};
int main()
{
String s1("abcd");
String s2(s1);
String s3("efghs");
s3 = s2;
cout<< "s1:" << s1.GetChar() << endl;
cout<< "s2:" << s2.GetChar() << endl;
cout << "s3:" << s3.GetChar() << endl;
return 0;
}
标签:string的深拷贝
原文地址:http://10622551.blog.51cto.com/10612551/1689550