【C++教程从0到1入门编程】第八篇:STL中string类的模拟实现

一、 string类的模拟实现

下面是一个列子
#include <iostream>
namespace y
{
	class string
	{
	public: 
		//string()            //无参构造函数
		//	:_str(nullptr)
		//{}

		//string(char* str)  //有参构造函数
		//	:_str(str)
		//{}

		string()
			:_str(new char[1])
		{
			_str[0] = '\0';
		}
		string(char* str)   //构造函数在堆上开辟一段strlen+1的空间+1是c_str
			:_str(new char[strlen(str)+1])
		{
			strcpy(_str, str); //strcpy会拷贝\0过去
		}

		//string(char* str="")   //构造函数在堆上开辟一段strlen+1的空间+1是c_str
		//	:_str(new char[strlen(str) + 1])
		//{
		//	strcpy(_str, str); //strcpy会拷贝\0过去
		//}
		size_t size()
		{
			return strlen(_str);
		}
		bool empty()
		{
			return _str == nullptr;
		}
		char& operator[](size_t i)  //用引用返回不仅可以读字符,还可以修改字符
		{
			return _str[i];
		}

		~string()          //析构函数
		{
			if (_str)
			{
				delete[] _str;
				_str = nullptr;
			}
		}
				const char* c_str() //返回C的格式字符串
		{
			return _str;
		}

	private:
		char* _str;
	};
	void TestString1()
	{
		string s1("hello");
		string s2;
		for (size_t i = 0; i < s1.size(); i++)
		{
			s1[i] += 1;
			std::cout << s1[i] << " ";
		}
		std::cout << std::endl;
		for (size_t i = 0; i < s2.size(); i++)
		{
			s2[i] += 1;
			std::cout << s2[i] << " ";
		}
		std::cout << std::endl;
	}

	void TestString2()
	{
		string s1("hello");
		string s2(s1);
		std::cout << s1.c_str() << std::endl;
		std::cout << s2.c_str() << std::endl;

		string s3("world");
		s1 = s3; //调试点这里,析构也是两次
		std::cout << s1.c_str() << std::endl;
		std::cout << s3.c_str() << std::endl;
	}
}

这段代码中,存在一定的问题,当我们调试时会发现!

默认的拷贝的构造函数出现的问题!

默认的赋值运算符重载出现的问题。!

        上述string类没有显式定义其拷贝构造函数与赋值运算符重载,此时编译器会合成默认的,当用s1构造s2时,编译器会调用默认的拷贝构造。最终导致的问题是,s1、s2共用同一块内存空间,在释放时同一块空间被释放多次而引起程序崩溃,这种拷贝方式,称为浅拷贝。

此时引出了概念浅拷贝,

浅拷贝:也称位拷贝,编译器只是将对象中的值拷贝过来。如果对象中管理资源,最后就会导致多个对象共享同一份资源,当一个对象销毁时就会将该资源释放掉,而此时另一些对象不知道该资源已经被释放,以为还有效,所以 当继续对资源进项操作时,就会发生发生了访问违规。要解决浅拷贝问题,C++中引入了深拷贝。

那么深拷贝呢?

二、string类的模拟实现

头文件代码:

#include<iostream>
#include<assert.h>
namespace yyw
{
	class string
	{
	public:
		typedef char* iterator;
	public:
		string(const char* str = "")        //构造函数
		{
			_size = strlen(str);
			_capacity = _size;
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}

		//string s2(s1)
		string(const string& s)
			:_str(nullptr)
			, _size(0)
			, _capacity(0)
		{
			string tmp(s._str);
			this->swap(tmp);
		}

		//s1=s3
		string& operator=(const string& s) //(string s)
		{
			//this->swap(s);
			string tmp(s._str);
			this->swap(tmp);
			return *this;
		}

		void swap(string& s)
		{
			std::swap(_str, s._str);
			std::swap(_size, s._size);
			std::swap(_capacity, s._capacity);
		}
		~string()                         //析构函数
		{
			if (_str)
			{
				delete[] _str;
				_size = _capacity = 0;
				_str = nullptr;
			}
		}

		//string(const string& s)   //拷贝构造

		void push_back(char ch)           //增加字符
		{
			if (_size == _capacity)      //增加空间
			{
				size_t newcapacity = _capacity == 0 ? 6 : _capacity * 2;
				char* tmp = new char[newcapacity + 1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;
				_capacity = newcapacity;
			}
			_str[_size] = ch;
			_size++;
			_str[_size] = '\0';    //_size的位置设置为\0
		}
		void append(char* str)     //追加字符串
		{
			size_t len = strlen(str);
			if (_size + len > _capacity)   //注意不能按2倍去增容
			{
				size_t newcapacity = _size + len;
				char* tmp = new char[newcapacity + 1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;
				_capacity = newcapacity;
			}
			strcpy(_str + _size, str);
			_size += len;
			//_str[_size + len] = '\0'; strcpy已经把\0拷贝过去了
		}

		//s1+='ch' s1就是this
		string& operator+=(char ch)
		{
			this->push_back(ch);
			return *this;
		}
		//s1+="ch" s1就是this
		string& operator+=(char* ch)
		{
			this->append(ch);
			return *this;
		}

		string& insert(size_t pos, char ch)       //在pos位置插入字符
		{
			assert(pos <= _size);
			if (_size == _capacity)
			{
				size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;
				char* tmp = new char[newcapacity + 1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;

				//delete[] _str;  //注意这里不能写反了
				_capacity = newcapacity;
			}
			size_t end = _size;
			while (end >= (int)pos)
			{
				_str[end + 1] = _str[end];
				end--;
			}
			_str[pos] = ch;
			_size++;
			return *this;
		}
		string& insert(size_t pos, char* str)     //在pos位置插入字符串
		{
			assert(pos < _size);
			size_t len = strlen(str);
			if (_size + len > _capacity)
			{
				size_t newcapacity = _size + len;
				char* tmp = new char[newcapacity + 1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;
				_capacity = newcapacity;
			}
			size_t end = _size;
			while (end >= (int)pos)
			{
				_str[end + len] = _str[end];   //这里是挪len个不是1个
				end--;
			}

			//strncpy也可以
			//strncpy(_str + pos, str, len);
			//strcpy会把\0拷贝过去,不可以

			//写个循环从pos依次往后放
			for (size_t i = 0; i < len; i++)
			{
				_str[pos] = str[i];
				pos++;
			}

			_size += len;
			//返回自己
			return *this;
		}

		string& erase(size_t pos, size_t len = npos)
		{
			assert(pos < _size);
			if (len >= _size - pos)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				size_t i = pos + len;
				while (i <= _size)
				{
					_str[i - len] = _str[i];
					i++;
				}
				_size = _size - len;
			}
			return *this;
		}

		size_t find(char ch, size_t pos)     //在pos位置查找字符
		{
			for (size_t i = pos; i < _size; i++)
			{
				if (_str[i] == ch)
				{
					return i;
				}
			}
			return npos;
		}
		size_t find(char* str, size_t pos)   //在pos位置查找字符串
		{
			char* p = strstr(_str, str);
			if (p == NULL)
			{
				return npos;
			}
			else
			{
				return (p - str);
			}
		}

		void resize(size_t newsize, char ch = '\0')  //填充字符ch
		{
			if (newsize < _size)   //第三种情况
			{
				_str[newsize] = '\0';
				_size = newsize;
			}
			else
			{
				if (newsize > _capacity)   //增加容量
				{
					size_t newcapacity = newsize;
					char* tmp = new char[newcapacity];
					strcpy(tmp, _str);
					delete[]_str;
					_str = tmp;
					_capacity = newcapacity;
				}
				for (size_t i = _size; i < newsize; i++)  //把字符ch往_size后面填
				{
					_str[i] = ch;
				}
				_size = newsize;
				_str[_size] = '\0';
			}
		}

		iterator begin()                //iterator迭代器的原理
		{
			return _str;
		}
		iterator end()
		{
			return (_str + _size);
		}

		const char* c_str()
		{
			return _str;
		}

		char& operator[](size_t i)   //重载[]可以遍历输出字符串,加&是既可以读,也可以写
		{
			assert(i < _size);
			return _str[i];
		}
		const char& operator[](size_t i) const
		{
			assert(i < _size);
			return _str[i];
		}

		//s1<s s1就是this
		bool operator<(const string& s)
		{
			int ret = strcmp(_str, s._str);
			return ret < 0;
		}
		bool operator<=(const string& s)
		{
			return *this < s || *this == s;
		}
		bool operator>(const string& s)
		{
			return !(*this <= s);
		}
		bool operator>=(const string& s)
		{
			return !(*this < s);
		}
		bool operator==(const string& s)
		{
			int ret = strcmp(_str, s._str);
			return ret == 0;
		}
		bool operator!=(const string& s)
		{
			return !(*this == s);
		}

		bool empty()
		{
			return _size == 0;
		}
		size_t size()                   //求字符串的大小
		{
			return _size;
		}
		size_t capacity()              //求字符串的容量
		{
			return _capacity;
		}

	private:
		char* _str;
		size_t _size;              //已经有多少个有效字符个数
		size_t _capacity;          //能存多少个有效字符个数 \0不是有效字符,\0是标识结束的字符

		static size_t npos;       //insert用的位置
	};
	size_t string::npos = -1;

	std::ostream& operator<<(std::ostream& _out, string& s) 	//重载输出运算符<<
	{
		for (size_t i = 0; i < s.size(); i++)
		{
			std::cout << s[i];
		}
		return _out;
	}
	std::istream& operator>>(std::istream& _in, string& s)     //重载输入运算符<<
	{
		//for (size_t i = 0; i < s.size(); i++)  错误写法
		//{
		//	std::cin >> s[i];
		//}
		while (1)
		{
			char ch;
			ch = _in.get();
			if (ch == ' ' || ch == '\n')
			{
				break;
			}
			else
			{
				s += ch;
			}
		}
		return _in;
	}
	//std::istream& operator>>(std::istream& _in, string &s)     //重载输入运算符<<
	//{
	//	//for (size_t i = 0; i < s.size(); i++)  错误写法
	//	//{
	//	//	std::cin >> s[i];
	//	//}
	//	while (1)
	//	{
	//		char ch;
	//		ch = _in.get();
	//		if ( ch == '\n')
	//		{
	//			break;
	//		}
	//		else
	//		{
	//			s += ch;
	//		}
	//	}
	//	return _in;
	//}
	void TestString1()
	{
		string s1;
		string s2("bit");
		for (size_t i = 0; i < s1.size(); i++)
		{
			std::cout << s1[i] << " ";
		}
		std::cout << std::endl;
		for (size_t i = 0; i < s2.size(); i++)
		{
			std::cout << s2[i] << " ";
		}
		std::cout << std::endl;
	}
	void TestString2()
	{
		string s1;
		string s2("bit");
		std::cout << s1 << std::endl;
		std::cout << s2 << std::endl;

		s1.push_back('b');
		std::cout << s1 << std::endl;

		s2.push_back(' ');
		std::cout << s2 << std::endl;

	

		s1 += 'a';
		std::cout << s1 << std::endl;


		s2.insert(1, 'a');
		std::cout << s2 << std::endl;

	

		std::cout << s2.size() << std::endl;
		std::cout << s2.capacity() << std::endl;
	}
	void TestString3()
	{
		string s1;
		std::cin >> s1;
		std::cout << s1 << std::endl;
	}
}

测试代码:

#define _CRT_SECURE_NO_WARNINGS   1
#include"string.h"
int main()
{
	yyw::TestString1();

	yyw::string s3("hello");
	yyw::string::iterator it = s3.begin();
	while (it != s3.end())
	{
		std::cout << *it << " ";
		it++;
	}
	std::cout << std::endl;
	for (auto e : s3)
	{
		std::cout << e << " ";
	}
	std::cout << std::endl;

	yyw::TestString2();

	yyw::TestString3();
	return 0;
}

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值