string的实现

来源:互联网 发布:算法的确定性 编辑:程序博客网 时间:2024/05/03 23:41

#include <iostream>
using namespace std;

class String
{
private:
 char *str;
 int size;
public:
 String (char * s="")
 {
  size=strlen(s);
  str=new char [size+1];
  strcpy_s(this->str,size+1,s);
 }
 String (String & c)
 {
  int n=strlen(c.str);
  str=new char [n+1];
  strcpy_s(str,n+1,c.str);
  size=c.size;
 }
 
 ~String ()
 {
   delete [] str;
 }
 String operator + (String & s);
 String operator = (String & s);
// String operator =(char * c);
 char& operator [] (int n);
 
 friend ostream & operator << (ostream& out,String &s)
 {
  int n=s.size;
  for (int i=0;i<n;i++)
   out<<s.str[i];
  return out;
 }
 friend istream & operator >> (istream& in,String & s)
 {
  in.getline(s.str,100,'/n');
  int len=strlen(s.str);
  s.size=len;
  return in;
 }
 bool operator ==(String & s);
};


String String ::operator +(String & s)
{
 String temp;
 delete [] temp.str;
 int len=size+s.size;
 temp.str=new char [len+1];
 temp.size=len;
 strcpy_s(temp.str,this->size+1,str);
 strcat_s(temp.str,sizeof (temp.str),s.str);
 return temp;
}
String String ::operator =(String & s)
{
 if (size!=s.size)
  {
   delete [] this->str;
   this->str=new char [s.size+1];
   this->size=s.size;
  }
 strcpy_s(this->str,size+1,s.str);
 return *this;
}

bool String ::operator ==(String & s)
{
 if (this->size!=s.size)
  return false;
 else
 {
  for (int i=0;i<s.size;i++)
  {
   if (str[i]!=s.str[i])
    return false;
  }
  return true;
 }
}

char& String ::operator [] (int n)
{
 return str[n];
}

原创粉丝点击