第一种:传统写法
//传统写法
#include <iostream>
using namespace std;
class String
{
public:
//构造函数
String(char* str = "")
:_str(new char[strlen(str) + 1])
{
strcpy(_str, str);
}
//析构函数
~String()
{
if (_str)
{
delete[] _str;
}
}
//拷贝构造函数
String(const String& s)
{
this->_str = new char[strlen(s._str) + 1];
strcpy(_str, s._str);
}
//赋值运算符重载
String& operator=(const String& s)
{
if (this != &s)
{
delete[] _str;
_str = new char[strlen(s._str) + 1];
strcpy(_str, s._str);
}
return *this;
}
private:
char* _str;
};
第二种:现代写法
//现代写法
#include <iostream>
using namespace std;
class String
{
public:
//构造函数
String(char* str = "")
:_str(new char[strlen(str) + 1])
{
strcpy(_str, str);
}
//析构函数
~String()
{
if (_str)
{
delete[] _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;
}
//或者更简单的方法(值传递)
String& operator=(const String& s)
{
swap(_str, s._str);
return *this;
}
private:
char* _str;
};