String类的C++实现

   可能很多人在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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值