重载String:Overload String

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值