C++中string的模拟实现

2020-01-06 15:42:08丽君

c++中的string类可以实现字符串对象的一系列操作,如下图就是从cplusplus上截取的string的一部分功能:

c++,string

接下来我就简单模拟几个函数实现 

首先,我们要给出完整的string类,包括构造函数,析构函数,私有成员char* str 

 

并且在类内声明要实现的函数(本文我只实现了operator=,operator[ ],pushback(),以及三个operator+=,五个insert等) 


#include<iostream>
#include<cstring>
using namespace std;

class String
{
 friend ostream& operator<< (ostream& os,String& s);
public:
 String(const char* str = "") //构造函数
 :_sz(strlen(str))
 ,_capacity(strlen(str)+1)
 ,_str(new char[strlen(str)+1])
 {
 cout<<"String(const char* str)"<<endl;
 strcpy(_str,str);
 }
 String(const String& s) //拷贝构造
 :_sz(s._sz)
 ,_capacity(strlen(s._str)+1)
 ,_str(new char[strlen(s._str)+1])
 {
 cout<<"String(const String& s)"<<endl;
 strcpy(_str,s._str);
 }
 ~String() 
 {
 cout<<"~String()"<<endl;
 if(*_str != NULL)
 {
 delete[] _str;
 _str = NULL;
 _sz = 0;
 _capacity = 0;
 }
 }
 String& operator= (const String& s);
 //String& operator= (const String& s);
 char& operator[] (int index);
 void Push_Back(char c);
 String& operator+= ( const String& str );
 String& operator+= ( const char* s );
 String& operator+= ( char c );
 String& insert ( size_t pos, const String& str );
 String& insert ( size_t pos1, const String& str, size_t pos2, size_t n );
 String& insert ( size_t pos, const char* s, size_t n);
 String& insert ( size_t pos, const char* s );
 String& insert ( size_t pos, size_t n, char c );
private:
 char* _str;
 int _sz;
 int _capacity;
};

分别在类外实现各功能:

1. operator= 

用一个已知对象给一个新对象赋值(效果与拷贝构造相同,但实现不同):实现这个运算符重载应该注意的是判断两个对象是否相等,并且参数与返回值是引用类型会提高效率 


String& String::operator= (const String& s)
{
 if(this != &s) //判断两个对象是否相等
 {
 delete[] _str;
 _str = new char[strlen(s._str)+1];
 strcpy(_str,s._str);
 _sz = s._sz;
 _capacity = s._capacity;
 }
 return *this;
}

赋值运算符重载还有一种比较简单的做法,即直接交换两个对象的字符串指针即可


String& String::operator= (const String& s)
{
 std::swap(_str,s._str);
 return *this;
}

2. operator[ ]

重载数组坐标[ ]是比较简单的,直接返回该对象的坐标即可


char& String::operator[] (int index)
{
 return _str[index];
}

//由于_str是指向该字符串的指针,_str[ index ]是对下标为index的字符的解引用,所以返回值类型为char