简单的string仅仅需要构造函数,拷贝构造,移动构造和移动赋值,operator=,析构函数等。如下:
#include<iostream>
#include<assert.h>
using namespace std;
namespace qyy
{class string{public:friend ostream& operator<<(ostream& out, const string& s);friend istream& operator>>(istream& in, const string& s);template <class T>void swap(T &t1, T& t2)//方便交换{T tmp = t1;t1 = t2;t2 = tmp;}typedef char* iterator;//迭代器是原生的指针iterator begin(){return _str;}iterator end(){return _str + _size;}//构造函数string(const char*str = ""):_size(strlen(str)) {_str = new char[strlen(str) + 1];strcpy(_str, str);_capacity = _size ;}//拷贝构造--左值引用版本string(const string& s1){string s(s1._str);_str = nullptr;swap(_str,s._str);swap(_size, s._size);swap(_capacity, s._capacity);}//operator=--左值引用版本string& operator= ( string s){if (this != &s)//防止自己给自己赋值{delete []_str;_str = nullptr;swap(_str, s._str);swap(_size, s._size);swap(_capacity, s._capacity);}return *this;}//右值引用版本的拷贝构造和operator=//移动构造string(string && s):_str(nullptr),_capacity(0),_size(0){swap(_str,s._str);swap(_size, s._size);swap(_capacity, s._capacity);}//移动赋值string& operator=(string&& s){if (this != &s){swap(_str, s._str);swap(_size, s._size);swap(_capacity, s._capacity);}return *this;}//operator[]char& operator[](size_t i){assert(_str);assert(i < _size);return *(_str + i);}~string(){delete[] _str;_str = nullptr;_size = _capacity = -1;}void reserve(size_t size)//增大空间{if (size > _capacity){char* tmp = new char[size + 1];//开新空间//拷贝数据strcpy(tmp, _str);//释放旧空间if(_str)//确保指针不为空delete[]_str;_str = tmp;_capacity = size;}}void resize(size_t size,const char ch = '/0')//开空间{//改变容量if (size < _size){//直接将_size改变就行_str[size] = '/0';_size = size;}else{if (size > _capacity)//增容reserve(size);//给新开辟的空间填充chwhile (_size < size){_str[_size++] = ch;}_str[_size] = '/0';//在末尾补充'/0'}}void push_back(char ch){if (_size == _capacity)//需要增容{size_t newcapacity = _capacity == 0 ? 10 : _capacity * 2;reserve(newcapacity);}_str[_size++] = ch;//尾插字符_str[_size] = '/0';}//operator+=string&operator+=(char ch){push_back(ch);return *this;}const char* c_str()const{return this->_str;}private:char* _str;size_t _size;size_t _capacity;//不包含最后的/0};ostream& operator<<(ostream&out,const string &s){out << s._str;return out;}istream& operator>>(istream& in, const string& s){in >> s._str;return in;}
}
测试代码用于测试string类:
#include"string.h"
int main()
{qyy::string s1;qyy::string s2("hhhh");s2 = s1;qyy::string s3(s2);return 0;
}