【C++】String类模拟实现

此程序为string类模拟实现,提供了深拷贝方式的拷贝构造函数+赋值运算符重载。
具体深浅拷贝的不同之处与实现方式,在下一篇博客。

#include<iostream>
#include<string>
using namespace std;
#include<string.h>
//构造+拷贝构造+析构+=重载。
namespace bite {
	class string {
	public:
		string(const char* str = "") {
			if (nullptr == str)
			{
				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(const string& s)
			:_str(nullptr)
		{
			string strtemp(s._str);
			swap(_str, strtemp._str);
		}
		~string() {
			if (_str) {
				delete[] _str;
				_str = nullptr;
			}
		}
		string& operator=(const string& s) {
			if (this != &s) {
				char* temp = new char[strlen(s._str) + 1];
				delete[] _str;
				strcpy(temp, s._str);
				_str = temp;
			//	string strtemp(s._str);
			//	swap(_str, strtemp._str);
			}
			return *this;
		}
		//string& operator=(string s) {
		//	swap(_str, s._str);
		//	return *this;
		//}
	private:
		char* _str;
	};
}
int main() {
	bite::string s1("hello");
	bite::string s2(nullptr);
	bite::string s3(s1);
	s2 = s3;
}
发布了53 篇原创文章 · 获赞 49 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43550839/article/details/102534086