C++中sting类的简单实现方法

2020-01-06 15:47:10刘景俊

String

在C++的学习生涯我中发现String类的功能十分强大,所以我们是很有必要模拟实现它的,况且在面试的时候模拟实现一个String类也是面试官经常会考的,但是因为外界因素的限制我们是不可能模拟的和库里的string一致的(C++库里的string功能更强大),所以今天我们只模拟实现string的基本功能-构造函数,拷贝构造函数,析构函数,赋值运算符重载,运算符+=的重载,运算符[]的重载,c_str(得到一个C风格的字符指针,可操作字符串),Size,Push_Back,Insert(深拷贝),以及用写时拷贝copy_on_write的方式实现基本的String类

深拷贝的方式


class String 
{ 
friend ostream &operator<<(ostream &os,String &s); 
public: 
String(const char *str=""); //全缺省的构造函数,解决空字符串的问题 
String(const String &ps); //深拷贝 
String &operator=(String s); 
String &operator+=(const char * s); 
const char *C_Str()const //得到C风格的字符指针 
{ 
return _pstr; 
} 
char &operator[](size_t index) 
{ 
return _pstr[index]; 
} 
size_t Size()const 
{ 
return _size; 
} 
void PushBack(char c); 
String &Insert(size_t pos,const char *str); 
//String &operator=(String &s) 
//{ 
// cout<<"String &operator=(String &s)"<<endl; 
// if(this != &s) 
// { 
// delete[]_pstr; 
// _pstr=new char[strlen(s._pstr)+1]; 
// strcpy(_pstr,s._pstr); 
// } 
// return *this; 
//} 
~String() 
{ 
cout<<"~String()"<<endl; 
if(_pstr != NULL) 
{ 
delete[]_pstr; 
_pstr=NULL; 
_size=0; 
_capacity=0; 
} 
} 
private: 
void CheckCapacity(int count); 
private: 
int _size; 
int _capacity; 
char *_pstr; 
}; 
ostream &operator<<(ostream &os,String &s) 
{ 
os<<s._pstr; 
return os; 
} 
String::String(const char *str) 
:_size(strlen(str)) 
,_capacity(strlen(str)+1) 
,_pstr(new char[_capacity]) 
{ 
cout<<"String()"<<endl; 
strcpy(_pstr,str); 
} 
String::String(const String &ps) 
:_size(ps._size) 
,_capacity(strlen(ps._pstr)+1) 
,_pstr(new char[_capacity]) 
{ 
cout<<"String(const String &ps)"<<endl; 
strcpy(_pstr,ps._pstr); 
} 
String &String::operator=(String s) 
{ 
cout<<"String &operator=(String s)"<<endl; 
std::swap(_pstr,s._pstr); 
std::swap(_size,s._size); 
std::swap(_capacity,s._capacity); 
return *this; 
} 
void String::CheckCapacity(int count) 
{ 
if(_size+count >= _capacity) 
{ 
int _count=(2*_capacity)>(_capacity+count)?(2*_capacity):(_capacity+count); 
char *tmp=new char[_count]; 
strcpy(tmp,_pstr); 
delete[]_pstr; 
_pstr=tmp; 
_capacity=_count; 
} 
} 
void String::PushBack(char c) 
{ 
CheckCapacity(1); 
_pstr[_size++]=c; 
_pstr[_size]=''; 
} 
String &String::operator+=(const char * s) 
{ 
CheckCapacity(strlen(s)); 
while(*s) 
{ 
_pstr[_size++]=*s; 
s++; 
} 
_pstr[_size]=''; 
return *this; 
} 
String &String::Insert(size_t pos,const char *str) 
{ 
char *tmp=new char[strlen(_pstr+pos)]; 
strcpy(tmp,_pstr+pos); 
CheckCapacity(strlen(str)); 
while(*str) 
{ 
_pstr[pos++]=*str; 
str++; 
} 
strcpy(_pstr+pos,tmp); 
return *this; 
}