string容器简单实现
作者:互联网
string字符串在代码编辑中常常出现,本文主要介绍string内部常用函数的实现过程,关键点包含运算符的重载,左值拷贝和右值拷贝,左值运算符重载和右值运算符重载及迭代器的实现过程。相关函数未完全给出,以后会不断更新,敬请期待
#include<iostream>
#include<cstring>
using namespace std;
class String
{
public:
String(const char* p = nullptr)
{
if (p != nullptr)
{
_pstr = new char[strlen(p) + 1];
strcpy(_pstr, p);
}
else
{
_pstr = new char[1];
*_pstr = '\0';
}
}
~String()
{
delete[]_pstr;
_pstr = nullptr;
}
//带左值引用的拷贝构造
String(const String& str)
{
_pstr = new char[strlen(str._pstr) + 1];
strcpy(_pstr, str._pstr);
}
//带左值引用的赋值运算符重载
String& operator=(const String& str)
{
if (this == &str)
return *this;
delete[]_pstr;
_pstr = new char[strlen(str._pstr) + 1];
strcpy(_pstr, str._pstr);
return *this;
}
//带右值引用的拷贝构造
String(String&& str)
{
_pstr = str._pstr;
str._pstr = nullptr;
}
//带右值引用的赋值运算符重载
String& operator=(String&& str)
{
if (this == &str)
return *this;
delete[]_pstr;
_pstr = str._pstr;
str._pstr = nullptr;
return *this;
}
int length() { return strlen(_pstr); }
const char* c_str() { return _pstr; }
bool operator==(const String& str) { return strcmp(_pstr, str._pstr) == 0; }
bool operator!=(const String& str) { return strcmp(_pstr, str._pstr) != 0; }
char& operator[](int val) { return _pstr[val]; }
bool operator>(const String& str) { return strcmp(_pstr, str._pstr) > 0; }
bool operator<(const String& str) { return strcmp(_pstr, str._pstr) < 0; }
friend String operator+(String& str, String& lhs);
friend ostream& operator<<(ostream& out, const String& str);
private:
char* _pstr;
class Iterator
{
public:
Iterator(char* p = nullptr)
:_p(p) {}
bool operator!=(const Iterator& it){return _p != it._p;}
void operator++(){++_p;}
char& operator*() { return *_p; }
private:
char* _p;
};
public:
Iterator begin(){return Iterator(_pstr);}
Iterator end(){return Iterator(_pstr + length());}
Iterator rbegin() { return Iterator(_pstr + length()); }
Iterator rend() { return Iterator(_pstr); }
};
ostream& operator<<(ostream& out, const String& str)
{
out << str._pstr;
return out;
}
String operator+(String& str, String& lhs)
{
/*
这里返回的是值,不是指针或者是引用,原因在于
局部对象出作用域后会析构,无法找到局部对象的地址
*/
String tmp;
tmp._pstr = new char[str.length() + lhs.length() + 1];
strcpy(tmp._pstr, str._pstr);
strcat(tmp._pstr, lhs._pstr);
return tmp;
}
int main()
{
String str("abc");
String str2("def");
String str3 = str + str2;
cout << str3 << endl;
string str4;
auto it = str3.begin();
/*
调用Iterator构造函数,begin返回的_pstr初始化_p
*/
for (; it != str3.end(); ++it)
{
cout << *it << " ";
}
cout << endl;
cout << (str == str2) << endl;
return 0;
}
标签:pstr,return,String,容器,._,char,str,简单,string 来源: https://blog.csdn.net/FDk_LCL/article/details/105515351