//C++String 类的常规写法
#include <iostream>
using namespace std;
class String
{
public:
//构造函数
String(char*str = "")
:_str(new char[strlen(str) + 1])
{
strcpy(_str, str);
}
//拷贝构造
String(const String &s)
{
_str = new char[strlen(s._str) + 1];
strcpy(_str, s._str);
}
//operator=的重载
String&operator=(const String &s)
{
if (this != &s)
{
/*delete[]_str;
_str = new char[strlen(s._str) + 1];
strcpy(_str, s._str);*/
char*tmp = new char[strlen(s._str) + 1];
strcpy(tmp, s._str);
delete[]_str;
_str = tmp;
}
return *this;
}
//析构函数
~String()
{
if (_str)
{
delete[]_str;
}
}
char *CStr()
{
return _str;
}
char& operator[](size_t index)
{
return _str[index];
}
private:
char*_str;
};
//C++String类的现代写法
#include <iostream>
using namespace std;
class String
{
public:
String(char*str="")
:_str(new char[strlen(str)+1])
{
strcpy(_str, str);
}
String(const String&s)
:_str(NULL)
{
String tmp(s._str);
swap(_str, tmp._str);
}
String&operator=(const String &s)
{
if(this != &s)
{
String tmp(s._str);
swap(_str, tmp._str);
}
return *this;
}
//对 operator= 优化
String&operator=(String s)
{
swap(_str, s._str);
return *this;
}
~String()
{
if (_str)
{
delete[]_str;
}
}
char *CStr()
{
return _str;
}
char& operator[](size_t index)
{
return _str[index];
}
private:
char*_str;
};
转载于:https://blog.51cto.com/10741125/1754454