此程序为string类模拟实现,提供了深拷贝方式的拷贝构造函数+赋值运算符重载。
具体深浅拷贝的不同之处与实现方式,在下一篇博客。
#include<iostream>
using namespace std;
//构造+拷贝构造+析构+=重载。
namespace bite {
class string {
public:
string(const char* str = "") {
//申请空间
_str = new char[strlen(str) + 1];
//存放字符
strcpy(_str, str);//复习下strcpy() 连同/0一起拷贝的
}
//第一种深拷贝的方法
string(const string& s)
:_str(new char[strlen(s._str)+1])
{
strcpy(_str,s._str);
}
~string() {
if (_str) {
delete[] _str;
_str = nullptr;
}
}
string& operator=(string s) {
swap(_str, s._str);
return *this;
}
private:
char* _str;
};
}