zoukankan      html  css  js  c++  java
  • 如何重载操作符和转换操作符

    using System;
     
    class Complex
    {
        public int i;
        public Complex(int i)
        {
            this.i = i;
        }
        //操作符重载,本质上是一个方法
        public static Complex operator +(Complex c1, Complex c2)
        {
            return new Complex(c1.i + c2.i);
        }
    }
    class TalentType
    {
        public int i;
        public double l;
        //针对不同的类型设计的构造器
        public TalentType(int i)
        {
            this.i = i;
        }
        public TalentType(double l)
        {
            this.l = l;
        }
        //自定义的转换函数
        public int ToInt32()
        {
            return this.i;
        }
        public double Todouble()
        {
            return this.l;
        }
     
        /*以下是操作符转换,本质上也是一个方法*/
     
        //隐式的类型操作符转换
        public static implicit operator TalentType(int i)
        {
            return new TalentType(i);
        }
        public static implicit operator TalentType(double l)
        {
            return new TalentType(l);
        }
        //显式的类型操作转换
        public static explicit operator Int32(TalentType t)
        {
            return t.i;
        }
        public static explicit operator double(TalentType t)
        {
            return t.l;
        }
     
    }
    class App
    {
        static void Main(string[] args)
        {
            //操作符重载
            Complex c1 = new Complex(3);
            Complex c2 = new Complex(4);
     
            Complex c3 = c1 + c2;
            Console.WriteLine("after c1 add c2,c3.i={0}", c3.i);
     
            //隐式操作符转换
            TalentType t1 = 10;
            TalentType t2 = 2.3;
     
            //显式操作符转换
            int i = (int)t1;
            double l = (double)t2;
     
            Console.Read();
        }
    }

  • 相关阅读:
    题解 P2168 【[NOI2015]荷马史诗】
    题解 P2607 【[ZJOI2008]骑士】
    题解 P4323 【[JSOI2016]独特的树叶】
    题解 P4074 【[WC2013]糖果公园】
    题解 P4552 【[Poetize6] IncDec Sequence】
    题解 P3469 【[POI2008]BLO-Blockade】
    题解 P5058 【[ZJOI2004]嗅探器】
    题解 P4767 【[IOI2000]邮局】
    题解 CF463D 【Gargari and Permutations】
    TensorFlow学习笔记之二——安装和运行
  • 原文地址:https://www.cnblogs.com/OwenWu/p/1673544.html
Copyright © 2011-2022 走看看