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;
};String类的深拷贝
最新推荐文章于 2024-05-03 12:36:30 发布
本文介绍了一个使用C++实现的自定义字符串类String。该类采用深拷贝和标准交换(idiom)等技术来确保资源管理的安全性,并提供了下标操作符及C字符串转换接口。此外,还展示了构造函数、析构函数以及赋值操作符的现代实现方式。
199

被折叠的 条评论
为什么被折叠?



