*在上次上机练习的基础上,增加针对字符串的运算符重载“==”(判断两个字符串对象是否相等),“+”(两个字符串拼接在一起)。
0412题目的基础上修改
#include<iostream>
#include<string.h>
using namespace std;
class String
{
private:
int len;
char* Str;
public:
void showStr()
{
cout<<"string:"<<Str<<",length:"<<len<<endl;
}
String()
{
len=0;
Str=NULL;
}
String(const char *p)
{
len=strlen(p);
Str=new char [len+1];
strcpy(Str,p);
}
String(String &r)
{
len=r.len;
if(len!=0)
{
Str=new char[len+1];
strcpy(Str,r.Str);
}
}
~String()
{
if(Str!=NULL)
{
delete[]Str;
Str=NULL;
}
}
//4月19号新增内容
friend bool operator == (String & s,String &d);
friend String operator +(String &s,String &d);
};
bool operator==(String &s,String &d)
{
if(strcmp(s.Str,d.Str)==0)
{
return 1;
}
return 0;
}
String operator+(String &s,String &d)
{
String c;
delete c.Str;
c.len=s.len+d.len;
c.Str=new char[c.len+1];
strcpy(c.Str,s.Str);
strcat(c.Str,d.Str);
return c;
}
int main ()
{
String s1("1235");
String s2("456");
if(s1==s2) cout<<"yes"<<endl;
else cout<< "no"<<endl;
String s3 ;
s3=s2+s1;
s3.showStr();
}
难点: 运算符重载的操作 首先声明友元函数 friend 类型 operator 需要重载的操作符(参数)