可能很多人在ms的时候都会碰到这个问题,我也碰到过。网上也有很多这样的资源,个人觉得有些实现还是存在着问题的。所以在我的博客中总结出来:
class String
{
public:
String(const char* str=NULL); //赋值构造兼默认构造函数(char)
String(const String &other);
String& operator=(const String &other); //operator=
String& operator=(const char *ch); //operator=
String& operator+(const String&other); //operator+
bool operator==(const String&other); //operator==
char& operator[](unsigned int);
size_t size(){return strlen(m_data)};
~String(){delete [] _string;};
private:
char *_string;
size_t _size;
friend ostream& operator<< (ostream&,String&);
}
//assign constructor & default constructor
String::String(const char *str)
{
int n;
if(str==NULL)
{
_string = 0;
_size = 0;
}
else
{
_size = strlen(str);
_string = new char[_size+1];
strcpy(_string, str);
}
}
//copy constructor
String::String(const String &rhs)
{
_size = rhs._size;
if(rhs._string == NULL)
_string = NULL;
else
{
_string = new char[_size+1];
strcpy(_string, rhs._string);
}
}
//= operator
String::String& operator=(const char *ch);
{
if(ch == NULL)
{
_size = 0;
_string = NULL;
}
else
{
_size = strlen(ch);
_string = new char[_size+1];
strcpy(_string, ch);
}
return *this;
}
String::String &operator =(const String&other)
{
if(this != &other)
{
delete []m_data;
_size = other._size;
if( other._string == NULL)
{
_string = NULL;
}
else
{
_string = new char[_size+1];
strcpy(_string, other._string);
}
}
return *this;
}
//operator []
String::char &operator[](unsigned int i)
{
assert(i>=0 && i<= _size)
return _string[i];
}
istream &operator>>(istream &io, String &s)
{
const int limit_string_size = 4096;
char inBuf[limit_string_size];
io >>setw(limit_string_size)>> intBuf;
s = intBuf;
return io;
}
ostream &operator<<(ostream &io, String &s)
{
return os<<s.c_str();
}
String::String &operator +(const String &rhs)
{
String newString;
if(rhs._string == NULL)
{
newString = *this;
}
else if(_string == NULL)
{
newString = rhs;
}
else
{
newString._size = strlen(_string)+strlen(other._string);
newString._string = new char[newString._size+1];
strcpy(newString._string, _string);
strcat(newString._string, rhs._string);
}
return newString;
}