C++练习
/*1. 根据课件上的String类进一步完成以下运算符重载函数的定义,并编写主函数测试。(1) friend String operator+(String &, char *);
(2) friend String operator-(String & str1, char * str2);
(3) friend String operator-(String & str1, String & str2);
*/
#include<iostream.h>
#include<string.h>
class String
{
private:
char *buf;
int length;
int Index(String &,String &);
int Index(String &,char *);
public:
String(char *s="good!")
{
length=strlen(s);
buf=new char[length+1];
strcpy(buf,s);
}
String(String &s)
{
length=s.length;
buf=new char[length+1];
strcpy(buf,s.buf);
}
~String()
{
delete []buf;
}
String & operator=(const String & str)
{
if(buf)
delete buf;
length=str.length;
buf=new char[str.length+1];
strcpy(buf,str.buf);
return *this;
}
char * isIn(const char ch)//在字符串中查找某个字符
{
char *cp=buf;
while(*cp)
{
if(*cp==ch)
return cp;
cp++;
}
return 0;
}
int isSubStr(const char *str)
{
if(strstr(buf,str))
return 1;
return 0;
}
int operator <(const char *str)
{
if( strcmp(buf, str)<0)
return 1;
return 0;
}
int operator >(const char *str)
{
if( strcmp(buf, str)>0)
return 1;
return 0;
}
int operator ==(const char *str)
{
if( strcmp(buf, str)==0)
return 1;
return 0;
}
void Print()
{
cout<<buf<<endl;
}
friend String operator +(const String & ,const String & );
friend String operator+(String &, char *);
friend String operator-(String & , char * );
friend String operator-(String & , String & );
};
int String::Index(String &s,String &t)
{
int i=0,j=0;
while (i<s.length && j<t.length)
{
if (s.buf[i]==t.buf[j])
{
i++;
j++;
}
else
{
i=i-j+1;
j=0;
}
}
if (j>t.length)
return i-t.length+1;
else
return 0;
}
int String::Index(String &s,char *t)
{
int i=0,j=0;
while (i<s.length && j<strlen(t))
{
if (s.buf[i]==t[j])
{
i++;
j++;
}
else
{
i=i-j+1;
j=0;
}
}
if (j>strlen(t))
return i-strlen(t)+1;
else
return 0;
}
String operator +(const String & str1,const String & str2)
{
String temp;
temp.length=str1.length+str2.length;
temp.buf=new char[temp.length+1];
strcpy(temp.buf,str1.buf);
strcat(temp.buf,str2.buf);
return temp;
}
String operator+(String &str1, char *str2)
{
String temp;
temp.length=str1.length+strlen(str2);
temp.buf=new char[temp.length+1];
strcpy(temp.buf,str1.buf);
strcat(temp.buf,str2);
return temp;
}
String operator-(String & str1, char * str2)
{
String temp;
char *p=str1.buf;
temp.length=str1.length-strlen(str2);
temp.buf=new char[temp.length+1];
for (int i=0;i<Index(str1,str2);i++)
temp.buf[i]=str1.buf[i];
p+=strlen(str2);
while((temp.buf[i++]=*p++)!=0);
return temp;
}
String operator-(String & str1, String & str2)
{
String temp;
char *p=str1.buf;
temp.length=str1.length-str2.length;
temp.buf=new char[temp.length+1];
for (int i=0;i<Index(str1,str2);i++)
temp.buf[i]=str1.buf[i];
p+=str2.length;
while((temp.buf[i++]=*p++)!=0);
return temp;
}
void main()
{
String str1,str2("Hello,"),str3("everyone!");
cout<<str2.isSubStr("lo")<<endl;
if(str2>"Ha") cout<<"true"<<endl;
str1=str2+str3;
str1.Print();
char *sp1="el";
if(str1.isSubStr(sp1))
str2=str1-sp1;
str2.Print();
}
请大家帮忙看看这个问题,哪里错了呢?不知道怎样改。谢谢!