20170419 运算符重载

*在上次上机练习的基础上,增加针对字符串的运算符重载“==”(判断两个字符串对象是否相等),“+”(两个字符串拼接在一起)。
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 需要重载的操作符(参数)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值