算法竞赛模板 重载运算符

①重载string()

以日期类CDate为例:

class CDate{
public:
    int y,m,d;
    CDate(int y,int m,int d):y(y),m(m),d(d){}
    operator string()
    {
        string s;
        stringstream ss;
        ss<<y<<"-"<<m<<"-"<<d;
        ss>>s;
        return s;
    }
};
int main()
{
    int y,m,d;
    while(cin>>y>>m>>d)
    {
        CDate date(y,m,d);
        cout<<(string)date<<endl;
    }
}

 

②重载cin cout +  -  *  /

以整数类Integer为例:

class Integer{
public:
    int a;
    Integer(int a):a(a){}
    Integer():a(0){}
    friend istream &operator>>(istream &is,Integer&x)
    {
        is>>x.a;
        if(!is)
            x=Integer();
        return is;
    }
    friend ostream &operator<<(ostream &os,const Integer&x)
    {
        os<<x.a;
        return os;
    }
    Integer operator+(const Integer&x)const
    {
        Integer t;
        t.a=this->a+x.a;
        return t;
    }
    Integer operator-(const Integer&x)const
    {
        Integer t;
        t.a=this->a-x.a;
        return t;
    }
    Integer operator*(const Integer&x)const
    {
        Integer t;
        t.a=this->a*x.a;
        return t;
    }
    Integer operator/(const Integer&x)const
    {
        Integer t;
        t.a=this->a/x.a;
        return t;
    }
};
int main()
{
    Integer a, b;
    while(cin>>a>>b)
    {
        cout<<a+b<<" "<<a-b<<" "<<a*b<<" "<<a/b<<endl;
    }
    return 0;
}

 

posted @ 2018-08-23 14:34  真想不出名字了  阅读(269)  评论(0编辑  收藏  举报