重载String:Overload String

来源:互联网 发布:小米电视 广告 知乎 编辑:程序博客网 时间:2024/05/16 10:50

#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
class String
{
private:
 char* ch;
 int size;
public:
 String(char *s="");
 String(const String &s);
 ~String(void);

 int length(void)const;
 String sub(int pos,int len);

 String& operator=(const String &s);
 String& operator=(char *s);

 bool operator==(const String& s)const;
 bool operator==(char *s)const;

 friend bool operator==(char *ch,const String& s);

};
String::String(char *s )
{
size=strlen(s)+1;
ch=new char[size];
strcpy(ch,s);
}

String::String(const String& s)
{
 size=s.size;
 ch=new char[size];
 if(ch==NULL) exit(0);
 for(int i=0;i<size;i++)
 {
  ch[i]=s.ch[i];
 }
}
int String::length(void)const
{
 return size;
}
String::~String(void)
{
 delete []ch;
}
String String::sub(int pos,int len)
{
 int subsize=size-pos-1;
 String temp;
 char *p,*q;
 if(subsize<=0)
  return temp;
 if(len>subsize)
  len=subsize;

 delete []temp.ch;

 temp.ch=new char[len+1];

 p=temp.ch;
 q=&ch[pos];
 for(int i=0;i<len;i++)
  *p++=*q++;
 *p=NULL;
 temp.size=len+1;
 return temp;

}
String& String::operator =(const String &s)
{
 if(s.size!=size)
 {
  delete []ch;
  ch=new char[s.size];
  size=s.size;
 }
 for(int i=0;i<size;i++)
  ch[i]=s.ch[i];
 return *this;
}
String& String::operator=(char *s)
{
 int len=strlen(s);
 if(size!=len+1)
 {
  delete[]ch;
  ch=new char[size];
  size=len+1;
 }
 strcpy(ch,s);
 return *this;
}

bool String::operator==(const String& s)const
{
 return(strcmp(ch,s.ch)==0);
}
bool String::operator==(char* s)const
{
return (strcmp(ch,s)==0);
}

bool operator==(char *ch,const String& s)
{
 return (strcmp(ch,s.ch)==0);
}
int _tmain(int argc, _TCHAR* argv[])
{
 String s1("data structure");
 String s2("structure");
 String s3;
 s3=s1.sub(5,9);
 char *my="structure";
 if(s3==s2)
  cout<<"good"<<endl;
 if(s2==my)
  cout<<"very good"<<endl;
 if(my==s2)
  cout<<"very very good"<<endl;
 return 0;
}

原创粉丝点击