普通的浅拷贝
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class String
{
public:
String(char* pStr = "")
{
if (NULL == pStr)
{
_pStr = new char[1];
*_pStr = '\0';
}
else
{
_pStr = new char[strlen(pStr) + 1];
strcpy(_pStr, pStr);
}
}
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(pTemp, s._pStr);
delete[] _pStr;
_pStr = pTemp;
}
return *this;
}
~String()
{
if (_pStr)
delete[] _pStr;
}
void print()
{
cout << _pStr << endl;
}
private:
char* _pStr;
};
int main()
{
String a("hello");
String b(a);
String c = "hello word";
a.print();
b.print();
c.print();
return 0;
}