#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
class String
{
public:
String(const char* s = "")
{
if (NULL == s)
{
_pstr = new char[1];
_pstr = "\0";
}
else
{
_pstr = new char[strlen(s) + 1];
strcpy(_pstr, s);
}
}
String(const String& s)
{
_pstr = new char[strlen(s._pstr) + 1];
strcpy(_pstr, s._pstr);
}
String& operator=(const String& s)
{
if (this != &s)
{
char* ptemp = new char[strlen(s._pstr) + 1];
strcpy(s._pstr,ptemp);
delete[] _pstr;
_pstr = NULL;
_pstr = ptemp;
}
}
~String()
{
if (NULL != _pstr)
{
delete[] _pstr;
_pstr = NULL;
}
}
private:
char* _pstr;
};
void test()
{
String s1("12345");
String s2(s1);
String s3 = s2;
}
int main()
{
test();
system("pause");
return 0;
}
实现深拷贝主要是为了解决在浅拷贝中所遇到的一块内存空间被多个对象共同使用的情况,最后在释放对象空间的时候就会省去很多不必要的麻烦。