String类的实现
1.
class String
{
public:
String(const char *str = NULL); // 构造函数
String(const String &other); // 拷贝构造函数
~String(); // 析构函数
String &operator = (const String &other); // 赋值函数
private:
char* m_data;
}
String::~String()
{
delete[] m_data;
}
String::String(const char*str)
{
if(str == NULL)
{
m_data = new char[1];
*m_data = '\0'
}
else
{
int length = strlen(str);
m_data = new char[length + 1];
strcpy(m_data,str);
}
}
String::String(const String &other)
{
int length = strlen(other.m_data);
m_data = new char[lenght + 1];
strcpy(m_data,other.m_data);
}
String &String::operator = (const String &other)
{
if(this == &other) return *this;
delete[] m_data;
int length = strlen(other.m_data);
m_data = new char[length + 1];
strcpy(m_data, other.m_data);
return *this;
}
2.
int strlen(const char *str)
{
assert(str != NULL);
int len = 0;
while((*str++) != '\0')
len++;
return len;
}
3.
void strcpy(char *strDest, char *strSrc)
{
assert((strDest != NULL) && (strSrc != NULL));
char *address = strDest;
while((*strDest++ = *strSrc++) != '\0');
return address;
}
4.
char* _cdecl strcat(char *dest, const char *src)
{
char* cp = dest;
while(*cp) cp++;
while(*cp++ = *src++);
return cp;
}
5.
int strCmp(char *src,char *dest)
{
while(*src == *dest && *src != '\0' && *dest != '\0')
{
src++;
dest++;
}
if(*src == '\0' && *dest == '\0')
ruturn 0;
else
return -1;
}