本篇采用浅拷贝的方式模拟实现String类,但此方法有缺陷!!!
浅拷贝思路:
当类里面有指针对象时,进行简单赋值即可。
//浅拷贝
class String
{
public:
String(char *str)
:_str(new char[strlen(str) + 1])
{
strcpy(_str, str);
}
String(const String& s)
{
_str = s._str;
}
String& operator=(const String& s)
{
if (this != &s)
{
_str = s._str;
}
return *this;
}
~String()
{
if (_str)
{
delete[] _str;
_str = NULL;
}
}
const char* c_str()
{
return _str;
}
private:
char *_str;
};
void Test3()
{
String s1("abcdef");
String s2 = s1;
cout << s1.c_str() << endl;
cout << s2.c_str() << endl;
}
结果为:
为什会出现上述情况的?
这里就需要使用深拷贝解决此缺陷,深拷贝下篇继续讲解……