0
点赞
收藏
分享

微信扫一扫

c++ face object----study simulatione string class

非衣所思 2022-03-16 阅读 37
c++
#include<iostream>
#include<string>
#include<string.h>
namespace mine{
	class string{
		public:
			typedef char* iterator;
			string(const char* str = "")
			:_size(strlen(str)),_capacity(_size){
				_str = new char[_size + 1];
				strcpy(_str,str);
			}
			void swap(string& s){
				std::swap(_str,s._str);
				std::swap(_size,s._size);
				std::swap(_capacity,s._capacity);
			}
		string(const string& s):_str(nullptr){
			string temp(s._str);
			swap(temp);
		}
		string& operator=(const string& s){
			if(this != &s){
				string temp(s);
				swap(temp);
			}
			return *this;
		}
		size_t size() const{
			return _size;
		}
		size_t capacity() const{
			return _capacity;
		}
		char& operator[](size_t pos){
			return _str[pos];
		}
		operator[](size_t pos) const{
			return _str[pos];
		}
		void clear(){//no delete to save time
			_size = 0;
			_str[0] = '\0';
		}
		iterator begin(){
			return _str;
		}
		iterator end(){
			return _str + _size;
		}
		~string(){
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}
		private:
			char* _str;
			size_t _size;//real length
			size_t _capacity;//all room
	};
};
举报

相关推荐

C++ class

【C++】string

c++ string

C++ string

C++——string

C++之string

C++——std::String

0 条评论