C#:继承多态的方法实现数的简单加减乘除运算

时间:2024-11-12 16:04:50
   // 定义一个抽象的父类
    abstract class Figure
    {
        //声明抽象方法:
        //父类中的所有家里人可以用的方法必须都应用到子类中
        abstract public object getValue();//或者用virtual但是后面必须声明主体部分{ return null; }
        abstract public Figure Add(Figure f1); //{ return null; }
        abstract public Figure Sub(Figure f1);
        abstract public Figure Mul(Figure f1);
        abstract public Figure Div(Figure f1);
    }
    // 实数子类
    class DoubleFigure : Figure
    {
        //声明一个double型字段来存放数据
        protected double _myDouble;
        //运行的时候调用实现初始化
        public DoubleFigure(double num1)
        {
            this._myDouble = num1;
        }
        // 重写父类中输出结果的方法
        public override object getValue()
        {
            return _myDouble;
        }
        //实数相加
        public override Figure Add(Figure f1)
        {
            double doublenum = (double)this.getValue() + (double)f1.getValue();
            //f1.getValue()实际执行的结果类型不由f1声明时的类型决定,而是由指向堆中的内容决定
            DoubleFigure df = new DoubleFigure(doublenum);
            return df;//这里返回值类型为什么不是Figure也可以
            //在堆中开辟的空间地址传给了父类中的变量------父类的变量指向子类中的实例
            //父类变量能传递给子类中变量是因为实际类型没有改变
        }
        //这里不能用运算符的重载:operator必须和public static一同使用,而override不能与static同用
        //public override Figure operator +(DoubleFigure f1)
        //{
        //    double doubleNum = (double)this.getValue() + (double)f1.getValue();
        //    DoubleFigure df = new DoubleFigure(doubleNum);
        //    return df;      
        //}
        // 实数相减
        public override Figure Sub(Figure f1)
        {
            double doubleNum = (double)this.getValue() - (double)f1.getValue();
            DoubleFigure df = new DoubleFigure(doubleNum);
            return df;
        }
        // 实数相乘
        public override Figure Mul(Figure f1)
        {
            double doubleNum = (double)this.getValue() * (double)f1.getValue();
            DoubleFigure df = new DoubleFigure(doubleNum);
            return df;
        }
        //实数相除
        public override Figure Div(Figure f1)
        {
            if ((double)f1.getValue()!=0)
            {
double doubleNum = (double)this.getValue() / (double)f1.getValue();
                DoubleFigure df = new DoubleFigure(doubleNum);   
                return df;         
            }  
            else
            {
                Console.WriteLine("除数不能为0!");
                return new DoubleFigure(0);
            }
        }
        //隐式转换方法实现DoubleFigure类型的数隐式转换为int型
        public static  implicit operator DoubleFigure(int myInt1)
        {
            return new DoubleFigure(myInt1);
        }
       static void Main(string[] args)
        {
            //父类的变量指向子类的实例
            Figure f1 = new DoubleFigure(6);//整数实例
            Figure f2 = new DoubleFigure(1.2); //实数实例
            DoubleFigure f3 = (DoubleFigure)f1.Div(f2);
            Console.WriteLine(f3.getValue()); 
            Console.ReadKey();
        }