每个对象自己开辟自己的空间,自己释放自己的空间
class String
{
public:
String(char* str="")
:_str(new char[strlen(str)+1])
{
cout << "String()" << endl;
memcpy(_str, str, sizeof(char)*(strlen(str) + 1));
}
~String()
{
if (_str)
{
delete[] _str;
}
cout << "~String()" << endl;
}
//传统写法
//String(const String& s)
// :_str(new char[strlen(s._str)+1])
//{
// strcpy(_str, s._str);
//}
//String& operator=(const String& s)
//{
// if (this != &s)
// {
// char* tmp = new char[strlen(s._str) + 1];
// delete[] _str;
// strcpy(tmp, s._str);
// _str = tmp;
// }
// return *this;
//}
//现代写法
String(const String& s)
:_str(NULL)
{
String tmp(s._str);
std::swap(_str, tmp._str);
}
//String& operator=(const String& s)
//{
// if (this != &s)//不能写成if ((*this) != s),因为左右类型不匹配,移位一个为String一个为cosntString
// {
// String tmp(s);
// std::swap(_str, tmp._str);
// }
// return *this;
//}
String& operator=( String s)//加cosnt也不行,两边类型不匹配,c++要格外小心cosnt
{
std::swap(_str, s._str);
return *this;
}
public:
char& operator[](int index)
{
return _str[index];
}
char* C_str()
{
return _str;
}
private:
char* _str;
};