以前对字符串的操作都是char,但是在C++中使用string更加的方便,那么底层的实现是怎样的呢?接下来我来实现一下:
#include <iostream>
class String;
class Iterator
{
public:
Iterator(String *ps,int ids):pstr(ps),index(ids){}
bool operator!=(const Iterator rhs)
{
return index == rhs.index;
}
char& operator*();
const Iterator operator++(int)
{
Iterator tmp(*this);
index++;
return tmp;
}
Iterator& operator++()
{
index++;
return *this;
}
private:
String *pstr;
int index;
};
#pragma warning(disable:4996);
class String
{
public:
typedef Iterator iterator;
String(char *ptr)
:mptr(new char[strlen(ptr)+1]())
{
strcpy_s(mptr,strlen(ptr)+1,ptr);
}
//String str2 = str1 + "world";
const String operator+(char* rhs)
{
char *tmp = new char[strlen(mptr) + strlen(rhs) + 1]();
strcpy_s(tmp,strlen(mptr)+1,mptr);
strcat(tmp,rhs);
String str(tmp);
delete[] tmp;
return str;
}
//String str4 = str1 + str2;
const String operator+(const String& rhs)
{
char *tmp = new char[strlen(mptr) + strlen(rhs.mptr) + 1]();
strcpy_s(tmp,strlen(mptr)+1,mptr);
strcat(tmp,rhs.mptr);
String str(tmp);
delete[] tmp;
return str;
}
//深拷贝
String(const String& rhs)
{
mptr = new char[strlen(rhs.mptr) + 1]();
strcpy_s(mptr,strlen(rhs.mptr)+1,rhs.mptr);
}
bool operator<(const String& rhs)
{
return strcmp(mptr,rhs.mptr) < 0;
}
bool operator!=(const String& rhs)
{
return strcmp(mptr,rhs.mptr) != 0;
}
char& operator[](int index)
{
return mptr[index];
}
iterator begin()
{
return iterator(this,0);
}
iterator end()
{
return iterator(this,strlen(mptr));
}
~String()
{
delete[] mptr;
mptr = NULL;
}
private:
char *mptr;
friend const String operator+(char *,const String&);
friend std::ostream& operator<<(std::ostream& ,const String& );
friend std::istream& operator>>(std::istream& ,const String& );
};
//String str3 = "hi" + str1;对象做右操作数,在类外实现
const String operator+(char *lhs,const String& rhs)
{
char *tmp = new char[strlen(lhs) + strlen(rhs.mptr) + 1]();
strcpy_s(tmp,strlen(lhs)+1,lhs);
strcat(tmp,rhs.mptr);
String str(tmp);
delete[] tmp;
return str;
}
std::ostream& operator<<(std::ostream& out,const String& rhs)
{
out << rhs.mptr;
return out;
}
std::istream& operator>>(std::istream& in,const String& rhs)
{
in >> rhs.mptr;
return in;
}
char& Iterator::operator*()
{
return (*pstr)[index];
}