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;
    }
  • 相关阅读:
    Linux系统(Centos)下安装Java环境配置步骤详述
    Linux系统(Centos)下安装nodejs并配置环境
    js中!~什么意思
    java jmap
    java jstat
    java jps
    JVM-GC日志分析
    JVM垃圾回收
    JVM垃圾回收--年轻代、年老点和持久代
    auth_basic 认证
  • 原文地址:https://www.cnblogs.com/kannyi/p/9523590.html
Copyright © 2011-2022 走看看