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();
        }
    }

  • 相关阅读:
    currentColor
    clip:rect()
    webkitAnimationEnd事件与webkitTransitionEnd事件
    正方体旋转demo
    由-webkit-transform-style:preserve-3d;所想
    设置网站的图标
    条件注释判断浏览器
    怎样动态地插入不会暴露给用户的JS文件
    IOC Unity
    C# 线程
  • 原文地址:https://www.cnblogs.com/OwenWu/p/1673544.html
Copyright © 2011-2022 走看看