码迷,mamicode.com
首页 > 其他好文 > 详细

String类的实现

时间:2015-05-17 18:41:19      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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;

}

String类的实现

标签:

原文地址:http://www.cnblogs.com/SnailProgramer/p/4510122.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!