zoukankan      html  css  js  c++  java
  • 算法竞赛模板 重载运算符

    ①重载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;
    }
  • 相关阅读:
    BZOJ1218:[HNOI2003]激光炸弹
    洛谷【P3407】散步
    洛谷【P1142】轰炸
    洛谷【P1358】扑克牌
    洛谷【P1236】算24点
    洛谷【P2003】平板
    TVYJ1266:费解的开关
    POJ1958:Strange Towers of Hanoi
    孤独地、凄惨地AK
    ios---scrollview用法总结
  • 原文地址:https://www.cnblogs.com/kannyi/p/9523590.html
Copyright © 2011-2022 走看看