operator重载运算符

operator关键字作用

       重载运算符

代码:

      //定义Fraction类,该类重载了+和*运算符,并允许将Fraction对象隐式转换为double类型对象
    class Fraction
    {
        int num, den;
        public Fraction(int num, int den)
        {
            this.num = num;
            this.den = den;
        }

        //重载“+”操作符
        //Fraction类型的对象a和b相加的结果是返回一个Fraction对象,
        //这个对象的num字段值是a和b的num字段的乘积,den字段值是a和b的den字段的乘积
        public static Fraction operator +(Fraction a, Fraction b)
        {
            return new Fraction(a.num + b.num, a.den +b.den);
        }

        //重载“*”操作符
        public static Fraction operator *(Fraction a, Fraction b)
        {
            return new Fraction(a.num * b.num, a.den * b.den);
        }

        //使用implicit,允许将Fraction类型对象隐式转换为doulbe类型对象
        public static implicit operator double(Fraction f)
        {
            return (double)f.num / f.den;
        }
    }

      //使用重载后的运算符
        Fraction a = new Fraction(1, 2);
      Fraction b = new Fraction(3, 7);
      Fraction c = new Fraction(2, 3);
       Console.WriteLine((double)(a * b + c));//输出结果为(1*3+2)/(2*3+3)

你可能感兴趣的:(operator重载运算符)